var express = require('express');
var mysql = require('mysql');
var conf = require('./config/conf');
var common = require('./config/common');
var TelegramBot = require('node-telegram-bot-api');
var TronWeb = require('tronweb')
var cors = require('cors');
var fs = require('fs');
var moment = require('moment');
var request = require('request-promise');

var login = require('./api/login');
var chart = require('./api/chart');
var table = require('./api/table');
var result = require('./api/result');
const { inline_keyboard, chatid, jndqunid} = require('./config/conf');

const route = express.Router();
var app = express();
app.use(cors())
app.use(login);
app.use(chart);
app.use(table);
app.use(result);
var apitrc = `https://api.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` ////https://api.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t //https://nile.trongrid.io/v1/accounts/${conf.czaddress}/transactions/trc20?limit=20&contract_address=TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj
var tzxz = "./img/tzxz.jpg"
var ksxz = "./img/ksxz.jpg"
var fengpancishu = 0,iskey,iszaliu,a, b, c,daxiao,danshuang,longhu,baozi,shunzi,duizi,value,date,minutes,isfengpan = false,iskaijiang = false,resultArray = [],resultid = "1",
resultCount = [
    {value :0},
    {value :0},
    {value :0},
    {value :0},
    {value :0},
    {value :0}
],
resultdxds = {
    big:0,
    small:0,
    odd:0,
    even:0,
    baozi:0,
    shunzi:0,
    duizi:0,
    longhu:3
},
fengpantime = "",
kaijiangtime = "";
var  HttpProvider = TronWeb.providers.HttpProvider;
var  tronWeb = new TronWeb(new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), conf.trxPrivateKey);
//new TronWeb(new HttpProvider("https://api.trongrid.io")
//
//
// , new HttpProvider("https://api.trongrid.io"), new HttpProvider("https://api.trongrid.io"), conf.trxPrivateKey);
 //new TronWeb("https://api.nileex.io", "https://api.nileex.io", "https://api.nileex.io", conf.trxPrivateKey);
var contractaddress_usdt = "TGDVN1UC4jrAz1ZsNsgW2jV9xmVpiADn1o"; //TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t //TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj
var server = app.listen(conf.port, function () {
    /*监听充值订单*/
    setInterval(function() {
        date = new Date();
        checkbetguoqi()
    },1000)
})

var bot = new TelegramBot(conf.token, {polling: true});
var allkeyword = ["游戏","/start","我要充值","🏧佣金提现","游戏规则","开始游戏","🏠代理中心","最近投注","账单记录","个人中心","实时佣金排名","取消","撤回","历史","上分","下分","大","小","单","双","豹子","对子","顺子","杀","T","哈","1","2","3","反水","余额"]
/*监听新的文字消息*/

bot.on("dice",(msg)=>{
    fashazi(msg)
})

bot.on('text', (msg) => {
    console.log('text==========',JSON.stringify(msg))
    if (msg.text=="大" || msg.text=="小" || msg.text=="单" || msg.text=="双" || msg.text=="豹子" || msg.text=="对子" || msg.text=="顺子" || msg.text=="杀" || msg.text=="哈") {
        return
    }
    if(msg.text.search(`\\+`)!=-1 && checkarray(msg.from.id,conf.adminid) && msg.reply_to_message){
            shangfenadmin(msg.text,msg.reply_to_message.from.id,(msg.reply_to_message.from.first_name?msg.reply_to_message.from.first_name:"")+(msg.reply_to_message.from.last_name?msg.reply_to_message.from.last_name:""),msg.message_id,msg.reply_to_message.from.username,msg.from.username,msg.reply_to_message.message_id,msg.chat.id)
    }else if(msg.text.search(`\\-`)!=-1 && checkarray(msg.from.id,conf.adminid) && msg.reply_to_message){
        xiafenadmin(msg.text,msg.reply_to_message.from.id,(msg.reply_to_message.from.first_name?msg.reply_to_message.from.first_name:"")+(msg.reply_to_message.from.last_name?msg.reply_to_message.from.last_name:""),msg.message_id,msg.reply_to_message.from.username,msg.from.username,msg.chat.id)
    }else if(msg.text=="签到"){
        qiandao(msg.text,msg.from.id,(msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""),msg.message_id,msg.from.username,msg.chat.id)
    }else if(msg.text=="cz" && checkarray(msg.from.id,conf.adminid)){
        isfengpan = false;
    }else if(msg.text=="游戏"){
        allgame(msg)
    }else if (msg.text.search("yj")==0 && checkarray(msg.from.id,conf.adminid)) {
        yongjintixian(msg.text,msg.reply_to_message.from.id,(msg.reply_to_message.from.first_name?msg.reply_to_message.from.first_name:"")+(msg.reply_to_message.from.last_name?msg.reply_to_message.from.last_name:""),msg.message_id,msg.reply_to_message.from.username,msg.from.username,msg.chat.id)
    }else if(msg.chat.id==conf.houtaiqunid) {
        if (msg.text.search("\\+")!=-1 || msg.text.search("\\-")!=-1 ) {
            topupgroup(msg)
        }else if(msg.text.search("qh")==0){
            checkqihao(msg)
        }else if(msg.text.search("qx")==0){
            backqihao(msg)
        }else if(msg.text.search("pc20qx")==0){
            pc20backqihao(msg)
        }else if(msg.text.search("pc28qx")==0){
            pc28backqihao(msg)
        }
    }



    if (msg.forward_date==undefined && msg.text){
        if (msg.chat.id==conf.chatid || msg.chat.id==conf.sxfqunid  || msg.chat.type=='private') {
            var msgtxt = msg.text;
            iskey = false;
            for (let index = 0; index < allkeyword.length; index++) {
                if (msgtxt.search(allkeyword[index])!=-1 || parseInt(msgtxt)%1==0 || tronWeb.isAddress(msgtxt)) {
                    iskey=true;
                }
            }
            console.log('iskey=====',iskey)
            if (iskey) {
                console.log('进来查库了');
                conf.pool.getConnection(function(err, connection) {
                    console.log('err====',err)
                    if (err) return err;
                    console.log(`SELECT * FROM users where telegramid = "${msg.from.id}"`)
                    connection.query(`SELECT * FROM users where telegramid = "${msg.from.id}"`,(error, result)=> {
                        console.log('result==',result)

                        if (result.length==0) {
                            var inviter_telegramid = msg.text.split(" ")[1];
                            if (!inviter_telegramid || parseInt(inviter_telegramid)%1!=0) {
                                inviter_telegramid = "无邀请人"
                            }
                            connection.query(`Insert into users (name,nickname,telegramid,register_time,inviter_telegramid) values ("${(msg.from.username?msg.from.username:"")}","${utf16toEntities((msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""))}","${msg.from.id}",now(),"${inviter_telegramid}");`,(error, result)=> {
                                connection.destroy();
                                if (error) return error;
                                if (msg.chat.id==conf.chatid) {
                                    main(msg);
                                }else if (msg.chat.id==conf.sxfqunid){
                                   sxf(msg);
                                }else if (msg.chat.type=='private') {
                                    privatemain(msg)
                                }
                            });
                        }else{
                            console.log('更新用户=====================')
                            connection.query(`update users set name =  "${(msg.from.username?msg.from.username:"")}",nickname = "${utf16toEntities((msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""))}" , lastchat_time = now() where telegramid =  "${msg.from.id}";`,(error, result)=> {
                                connection.destroy();
                                if (error) return error;
                                if (msg.chat.id==conf.chatid) {
                                    console.log("=====进入主函数")
                                    main(msg);
                                }else if (msg.chat.id==conf.sxfqunid){
                                    console.log("=====进入上下分主函数")
                                   sxf(msg);
                                }else if (msg.chat.type=='private') {
                                    console.log("=====进入私有群主函数")
                                    privatemain(msg)
                                }
                            });
                        }
                    })
                })
            }
        }
    }
});

/*监听错误*/
bot.on('error', (error) => {
    console.log("监听到普通错误："+date+error);
});
bot.on('polling_error', (error) => {
    console.log("监听到轮循错误："+date+error);
});
bot.on('webhook_error', (error) => {
    console.log("监听到webhook错误："+date+error);
});

function pc28backqihao(msg) {
    var qihao = msg.text.split("pc28qx")[1];
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM pcbet where resultid = "${qihao}";`,(error, result)=> {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users set balance = balance ${(result[index].result-result[index].amount<0?"+"+(result[index].amount-result[index].amountreturn):"-"+(result[index].result-result[index].amount-result[index].amountreturn))} where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`,{
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}delete from pcbet where resultid = "${qihao}";`,(error, result)=> {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}

function checkbetguoqi() {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and result is null and time < "${moment(Math.round(date)-300000).format("YYYY-MM-DD HH:mm:ss")}"`,(error, result)=> {
            if (error) throw error;
            if(result[0]){
                bot.sendMessage(conf.chatid,`<b>投注已经过期,本期下注金额不退</b>\n\n用户：<a href="http://t.me/${result[0].name}">${utf16toEntities(result[0].firstname)}</a> \n下注：${result[0].guess}-${result[0].amount} `,{
                    parse_mode:"HTML",
                    disable_web_page_preview:true
                })
                //退回的
                /*connection.query(`update bet set result = -1 where id = "${result[0].id}";update users set balance = balance + ${result[0].amount} where telegramid = "${result[0].telegramid}";`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                });*/
                connection.query(`update bet set result = -1 where id = "${result[0].id}";`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                });
            }else{
                connection.destroy();
            }

        });

    })
}

function pc20backqihao(msg) {
    var qihao = msg.text.split("pc20qx")[1];
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM jndbet where resultid = "${qihao}";`,(error, result)=> {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users set balance = balance ${(result[index].result-result[index].amount<0?"+"+(result[index].amount-result[index].amountreturn):"-"+(result[index].result-result[index].amount-result[index].amountreturn))} where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`,{
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}delete from jndbet where resultid = "${qihao}";`,(error, result)=> {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}

function backqihao(msg) {
    var qihao = msg.text.split("qx")[1];
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and resultid = "${qihao}";`,(error, result)=> {
            if (error) return error;
            var backsql = ""
            for (let index = 0; index < result.length; index++) {
                backsql += `update users set balance = balance ${(result[index].result-result[index].amount<0?"+"+(result[index].amount-result[index].amountreturn):"-"+(result[index].result-result[index].amount-result[index].amountreturn))} where telegramid = "${result[index].telegramid}";`;
            }
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注已经退回</b>\n\n${allbet}`,{
                parse_mode: 'HTML'
            })
            connection.query(`${backsql}delete from bet where type = "${conf.type}" and resultid = "${qihao}";`,(error, result)=> {
                connection.destroy();
                if (error) return error;
            });
        });

    })
}



function fashazi(msg) {
    conf.pool.getConnection(function(err, connection) {
    console.log('扔色子====',err)
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${msg.from.id}" and result is null order by id desc;`,(error, result)=> {
            console.log('扔色子查询=====',error)
            connection.destroy();

            if (error) return error;
            console.log('result[0]====',result[0])
            console.log('msg.dice.value',msg.dice.value)
            if (result[0]) {
                if (!result[0].one) {
                    conf.pool.getConnection(function(err, connection) {
                        console.log(err)
                        if (err) return err;
                        connection.query(`update bet set one = "${msg.dice.value}" where type = "${conf.type}" and resultid = "${result[0].resultid}";update result set one = "${msg.dice.value}" where id = "${result[0].resultid}";`,(error, result)=> {
                            connection.destroy();
                        });

                    })
                }else if (!result[0].two) {
                    conf.pool.getConnection(function(err, connection) {
                        console.log(err)
                        if (err) return err;
                        connection.query(`update bet set two = "${msg.dice.value}" where type = "${conf.type}" and resultid = "${result[0].resultid}";update result set two = "${msg.dice.value}" where id = "${result[0].resultid}";`,(error, result)=> {
                            console.log('twoerror===',error)
                            connection.destroy();
                        });

                    })
                }else if (!result[0].three) {
                    conf.pool.getConnection(function(err, connection) {
                        if (err) return err;
                        connection.query(`update bet set three = "${msg.dice.value}" where type = "${conf.type}" and resultid = "${result[0].resultid}";update result set three = "${msg.dice.value}" where id = "${result[0].resultid}";`,(error, result)=> {
                            console.log('threeerror===',error)
                            connection.destroy();
                            setResult(msg)
                        });

                    })
                }
            }
        });

    })
}

function checkqihao(msg) {
    var qihao = msg.text.split("qh")[1];
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and resultid = ${qihao};`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            var allbet = ""
            for (let index = 0; index < result.length; index++) {
                allbet += `${result[index].firstname}(<code>${result[index].telegramid}</code>)\n  <code>${result[index].guess}</code><code>${result[index].amount}</code> - 返奖：<code>${result[index].result}</code>\n`;

            }
            bot.sendMessage(msg.chat.id, `<b>${qihao}全部下注</b>\n\n${allbet}`,{
                parse_mode: 'HTML'
            })
        });

    })
}

function topupgroup(msg) {
    if (msg.text.search("\\+")!=-1) {
        var czjine = "+"+msg.text.split("+")[1];
        var telegramid = msg.text.split("+")[0];
    }

    if (msg.text.search("\\-")!=-1) {
        var czjine = "-"+msg.text.split("-")[1];
        var telegramid = msg.text.split("-")[0];
    }
    if (telegramid%1!=0 || telegramid.length<9) {
        return
    }
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;

        connection.query(`SELECT * FROM users where telegramid = ${telegramid};`,(error, result)=> {
            if (error) return error;
            connection.query(`update users set balance = balance ${czjine} where telegramid = "${telegramid}";`,(error, res)=> {
                connection.destroy();
                if (error) return error;

                if(result.length>0){
                     bot.sendMessage(conf.houtaiqunid, `用户: ${(result[0].nickname?result[0].nickname:"")}\nID: <code>${result[0].telegramid}</code>\n余额:${result[0].balance}\n充值金额：${czjine}`,{
                        parse_mode: 'HTML'
                    })
                }else{
                    bot.sendMessage(msg.chat.id, `用户未注册`,{
                        parse_mode: 'HTML'
                    })
                }


            });
        });

    })
}

/*监听内联键盘*/
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
    if (callbackQuery.data.search("fanye")==0) {
        fanyecktd(callbackQuery)
    }
    if (!isfengpan) {
        switch (callbackQuery.data) {
            case "6":
                getBalance(callbackQuery.from.id,callbackQuery.from.username,callbackQuery.id);
                break;
            case "7":
                getMyBet(callbackQuery.from.id,callbackQuery.from.username,callbackQuery.id);
                break;
            case "8":
                getTodayBill(callbackQuery.from.id,(callbackQuery.from.first_name?callbackQuery.from.first_name:"")+(callbackQuery.from.last_name?callbackQuery.from.last_name:""),callbackQuery.id);
                break;
            case "9":
                getReturnWater(callbackQuery.from.id,callbackQuery.from.username,callbackQuery.id);
                break;
            case "qxorder":
                qxorder(callbackQuery)
                break;
            case "lstj":
                tongji(callbackQuery.from.id,callbackQuery.from.username,callbackQuery.id);
                break;
            case "qbtx":
                quanbutixian(callbackQuery.from.id,callbackQuery.message.chat.id,callbackQuery.message.message_id,callbackQuery.id)
                break;
            case "cktd":
                cktd(callbackQuery)
                break;
            case "backdaili":
                backdaili(callbackQuery)
                break;
            default:
                break;
        }
    }
});

function allgame(msg) {
    bot.sendMessage(msg.chat.id, `点击下方按钮进入游戏群`,{
		parse_mode: 'HTML',
		disable_web_page_preview:true,
		reply_markup: {
			inline_keyboard: conf.game_line_keyboard
		}
	})
}


function start(msg) {
    bot.sendMessage(msg.chat.id, `<b>📣${((msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""))}，感谢您的关注!</b>\n\n\n<a href="${conf.youxigrouplink}">手摇快三游戏</a>开奖采用<a href="https://core.telegram.org/api/dice">Telegram官方骰子</a>\n以保证游戏过程的绝对随机和绝对公平 ！`,{
		parse_mode: 'HTML',
		disable_web_page_preview:true,
		reply_markup: {
			inline_keyboard: conf.start_line_keyboard
		}
	})
    .then(res=>{
        bot.sendMessage(msg.chat.id,`<b>✅已开启键盘</b>`,{
            parse_mode:"HTML",
            reply_markup: {
                keyboard: conf.keyboard,
                resize_keyboard:true
            }
        })
    })
}


function fuli(msg) {
    bot.sendMessage(msg.chat.id, `（福利活动多多）
下注看好规则
切勿超额下注，否则不负责任
认准财务ID
充值直接进群。https://t.me/+321

唯一收款地址:
TWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd

每日首次充值以上100rmb送6%🎉

每次充值活动只能选一个 ❗️❗️❗️

后续充值笔笔送4%🎉🎉🎉

（送彩金上限388RMB）💰
发现刷彩金的直接扣除拉黑
（骰子每天仅限三次）
下注流水实时反1%🎉
当天负盈利反5%）
负盈利每日12:00自动反5%
负盈利回水须满足1倍流水才可提现！

⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️⚜️
抽奖模式每次单笔充值300RMB以上
认准财务ID: @Xiy99999
即可获得一次抽奖机会
🎲🎲摇骰子活动🎲🎲🔥
即日起凡是在夕阳集团充值达到要求的玩家，上分成功后均可参加摇骰子活动:充值300以上即可抽奖
🎁骰子🎲出现一个6，奖励38RMB
🎁骰子🎲出现两个6，奖励66 RMB
🎁骰子🎲出现三个6，奖励666 RMB
充值2000以上
🎁骰子🎲出现一个6，奖励108RMB
🎁骰子🎲出现两个6，奖励333 RMB
🎁骰子🎲出现三个6，奖励2222 RMB

(摇骰子要根据客服的指示摇！！)
快三每日签到福利🎁🎁🎁
每日充值500以上
凌晨12点-1:00开始签到
过时无效，重新归零
第一天  6               第二天12
第三天18               第四天28
第五天38               第六天48
第七天58
领取要求如下当天投注满20把(每把10以上满足要求即可联系客服申请，领取的福利1倍流水即可下分）

爆庄奖励 🎁🎁🎁
1w奖励188.  5w奖励588.   10w奖励888.   30w奖励1888  50w奖励2888
100w奖励18888
输+赢活动 🎁🎁🎁

当天输赢1000以上参加活动
发三个骰子
一个6奖励6
二个6奖励38
三个6奖励88

特别提醒，晚上12点过后 一律按客服提示掷色子
所有奖励1倍流水下分。

每天12:00点福利 🧧🧧🧧
充值满3000以上可参与并有效
会在上分内部群聊里发1000红包
领取到奖励.1倍流水可下分


（每人每天反限三次机会）

（充值必须打满1倍流水才可下分）
（防止洗钱 多次，上多少下多少⚠️）
同一个人，转帐，每个帐户名不一样
加上，上多少下多少，直接扣分拉黑
判为洗钱，⚠️⚠️⚠️别来找事`,{
    parse_mode: 'HTML',
    disable_web_page_preview:true,
});
}


function guizehuodong(msg) {
    bot.sendMessage(msg.chat.id, `🔥🔥【强盛集团手摇快三骰子玩法押注赔率介绍】🔥🔥
✅ 玩家自己手摇TG官方表情包骰子，玩家下注后自己掷出三颗骰子，采用前三个骰子点数决定胜负！多骰子只取前三颗.具有随机性，玩家自己摇任何人无法操控.保证绝对的公开、公平、公正！✅

下注单位为RMB（上下分100RMB起）
上下分支持微信，支付宝，USDT
------------------------
🎲单式玩法🎲： （指令：单100）  赔率/2倍
（🚫下注额度1-50000）
【小】：总点数 4至10
【大】：总点数 11至17
【单】：总点数为 5，7，9，11，13，15，17
【双】：总点数为 4，6，8，10，12，14，16

🎲复式玩法🎲：（指令：大单100）
（🚫下注额度1-50000）
【大单】11，13，15，17  （赔率3.5倍）
【小双】4，6，8，10     （赔率3.5倍）
【大双】12，14，16    （赔率4.5倍）
【小单】5，7，9        （赔率4.5倍）
【顺子】—3个骰点连数     （赔率8倍）
【对子】—3个骰两个相同       （赔率2.2倍）

------------------------
🎲特殊玩法🎲：💵杀指定总点数💵
（押注口令:点数+杀+金额）
（🚫下注限额1-20000）
例：15杀100
总点数:4，17                 赔率88倍
总点数:5，16                 赔率36倍
总点数:6，15                 赔率15倍
总点数:7，14                 赔率13倍
总点数:8，13                 赔率9倍
总点为:9，12                 赔率7倍
总点数:10，11               赔率7倍

------------------------
🎲豹子玩法🎲
（🚫限注限额1-10000）
（指令：豹子+金额）
豹子: （赔率66倍）
例:豹子100

点豹玩法（指令：数字+豹子+金额）
例：1豹子100、2豹子100 （赔率188倍）  🔥

🔥🔥龙虎斗玩法🔥🔥（指令：龙100）
 （🚫下注额度1-50000）
龙虎斗：第一个骰子大于第三个骰子为龙赢，第三个骰子大于第一个骰子为虎赢，第一个和第三个一样大为合，出合庄家杀龙和虎

龙:（赔率2倍）
虎:（赔率2倍）
合:（赔率8倍）

🅰️ 查询命令
发送【余额】即可查询当期投注数据及余额信息
发送【历史】/【历史10】/【历史20】即可查询历史开奖
发送【取消】即可取消当前所有下注


------------------------
实时反水1%，代理1%


⚠️温馨提示：
①、一切以机器人系统录入为准，无争议！下注后必须摇完三颗骰子.只摇一粒或者两粒不返还下注金额。
②：凡是游戏程序出错期间，利用bug进行套利的，我司有权扣除盈利部分，并清除所有余额充公，不扯皮，请各位玩家遵循规则娱乐 ！
③：下注后摇完三颗骰子才能继续下注，追注不算。
④：倍投可以打，倍投需最大下注金额下注5次才能下分，四期认定倍投，具体定义：每连续下注四期中，最后一期中奖的下注金额＞前三期未中奖下注金额之和，单式和组合分开计算。
举个例子：单式玩法100-200-400-800，前面三期没中，第四期下注800中了，则需要800下注5次方可下分
金额是在翻倍的增加下注   就认定是倍投
防止有人钻漏洞
⑤：本群仅支持白资上分，如发现入款后账户冻结，下分保留24小时候处理，并转1元核对防止一道电诈资金，上分默认此规则，不扯皮！客服怀疑有黑资有权利选择同名下分！
 --------------------------------------

超过投注范围的投注中了无效，只返本，没中不退不赔，请各位老板严格按照投注范围投注，不要超过投注上限！
  --------------------------------------
以上玩法以免部分人理解偏差造成误解请在押注前咨询公群管理人员！
玩法赔率最终解释权归🎲强盛集团所有！`,{
		parse_mode: 'HTML',
		disable_web_page_preview:true,
	});
}

function kaishiyouxi(msg) {
    bot.sendMessage(msg.chat.id, `<a href="${conf.youxigrouplink}">加入群组，开始游戏！</a>`,{
		parse_mode: 'HTML',
		disable_web_page_preview:true,
	});
}

function zuijintouzhu(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = '${msg.from.id}' and result >=0 order by id desc LIMIT 50;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            console.log(result);
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (result[index].result == 0) {
                    result_money = `❌`
                }else{
                    result_money = `✅`
                }
                myBet = `${myBet}${result_money} <code>${result[index].resultid}</code> - ${result[index].guess} - <code>${result[index].amount}</code>\n`;
            }
            bot.sendMessage(msg.chat.id, `<b>最近50条投注记录</b>\n\n${myBet}`,{
                parse_mode:"HTML"
            })
        });
    });
}

function zhangdanjilu(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        console.log(err)
        connection.query(`SELECT * FROM pay where telegramid = '${msg.from.id}' and state = 1 and way = "群内管理上分" order by id desc LIMIT 10;SELECT * FROM withdrawal where telegramid = '${msg.from.id}' and state = 1 order by id desc LIMIT 10;SELECT * FROM jiangli where telegramid = '${msg.from.id}' order by id desc LIMIT 10;`,(error, result)=> {
            console.log(error)
            if (error) return error;
            connection.destroy();
            var chongzhi = "";
            var tixian = "";
            var jiangli = "";
            for (let index = 0; index < result[0].length; index++) {
                chongzhi = `${chongzhi}【${result[0][index].applytime.split("2023-")[1].substring(result[0][index].applytime.split("2023-")[1].length-3,result[0][index].applytime.split("2023-")[1])}】${result[0][index].amount}${conf.coin}\n`;
            }
            for (let index = 0; index < result[1].length; index++) {
                tixian = `${tixian}【${result[1][index].applytime.split("2023-")[1].substring(result[1][index].applytime.split("2023-")[1].length-3,result[1][index].applytime.split("2023-")[1])}】${result[1][index].amount}${conf.coin}\n`;
            }

            for (let index = 0; index < result[2].length; index++) {
                jiangli = `${jiangli}【${result[2][index].time.split("2023-")[1].substring(result[2][index].time.split("2023-")[1].length-3,result[2][index].time.split("2023-")[1])}】${result[2][index].type} ${result[2][index].amount}${conf.coin}\n`;
            }
            bot.sendMessage(msg.chat.id, `<b>最近20条账单</b>\n\n充值:\n<code>${chongzhi}</code>\n提现:\n<code>${tixian}</code>`,{
                parse_mode:"HTML"
            })
        });
    });
}

function cktd(callbackQuery) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where inviter_telegramid = '${callbackQuery.from.id}' limit 20 ;SELECT count(*) FROM users where inviter_telegramid = '${callbackQuery.from.id}';`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var list = ""
            for (let index = 0; index < result[0].length; index++) {
                if (result[0][index].name=="") {
                    list += `${index+1}.${(result[0][index].nickname==null?"未知用户":result[0][index].nickname)}\n`;
                }else{
                    list += `${index+1}.<a href="https://t.me/${result[0][index].name}">${(result[0][index].nickname==null?"未知用户":result[0][index].nickname)}</a>\n`;
                }
            }
            if (list=="") {
                list = '您还没有团队成员，请再接再厉哦！'
            }
            var allbuttonarray = []
            if (result[1][0]["count(*)"]>20) {
                allbuttonarray = [[{text:"➡️下一页",callback_data:"fanye_2"}]]
            }
            allbuttonarray.push([{text:"返回",callback_data:"backdaili"}])
            bot.editMessageText(`${list}`,{
                chat_id:callbackQuery.message.chat.id,
                message_id:callbackQuery.message.message_id,
                parse_mode:"HTML",
                disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:allbuttonarray
                }

            })
        });
    });
}

function fanyecktd(callbackQuery) {
    var yeshu = parseInt(callbackQuery.data.split("_")[1])
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where inviter_telegramid = '${callbackQuery.from.id}'  limit ${(yeshu-1)*20},20;SELECT count(*) FROM users where inviter_telegramid = '${callbackQuery.from.id}';`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var list = ""
            for (let index = 0; index < result[0].length; index++) {
                if (result[0][index].name=="") {
                    list += `${index+1}.${(result[0][index].nickname==null?"未知用户":result[0][index].nickname)}\n`;
                }else{
                    list += `${index+1}.<a href="https://t.me/${result[0][index].name}">${(result[0][index].nickname==null?"未知用户":result[0][index].nickname)}</a>\n`;
                }
            }
            if (list=="") {
                list = '您还没有团队成员，请再接再厉哦！'
            }
            var allbuttonarray = []
            var allbuttonarray = [[{text:"⬅️上一页",callback_data:`fanye_${yeshu-1}`}]]
            if(yeshu==1){
                allbuttonarray = [[{text:"➡️下一页",callback_data:`fanye_${yeshu+1}`}]]
            }else if (result[0].length==20) {
                allbuttonarray = [[{text:"⬅️上一页",callback_data:`fanye_${yeshu-1}`},{text:"➡️下一页",callback_data:`fanye_${yeshu+1}`}]]
            }
            allbuttonarray.push([{text:"返回",callback_data:"backdaili"}])
            bot.editMessageText(`${list}`,{
                chat_id:callbackQuery.message.chat.id,
                message_id:callbackQuery.message.message_id,
                parse_mode:"HTML",
                disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:allbuttonarray
                }

            })
        });
    });
}

function usercenter(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = '${msg.from.id}' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>📇个人中心</b>\n\n用户账号：<code>${result[0].telegramid}</code>\n用户昵称：<code>${((msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""))}</code>\n游戏余额：<code>${result[0].balance}元</code>\n\n累计流水：<code>${result[0].zongliushui}</code>`,{
                parse_mode:"HTML"
            })
        });
    });
}

function dailizhongxin(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*) FROM users where inviter_telegramid = '${msg.from.id}' ;SELECT count(*) FROM users where inviter_telegramid = '${msg.from.id}' and lastchat_time like '${moment().format("YYYY-MM")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}';
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}' and time like '${moment().format("YYYY-MM-DD")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}' and time like '${moment().format("YYYY-MM")}%' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>邀请好友前来游戏,永久享受${conf.yongjin*100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${msg.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)']?result[0][0]['count(*)']:0)}人（活跃：${(result[1][0]['count(*)']?result[1][0]['count(*)']:0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)']?result[2][0]['sum(amount)']*conf.yongjin:0)}（当日：${(result[3][0]['sum(amount)']?result[3][0]['sum(amount)']*conf.yongjin:0)}    当月：${(result[4][0]['sum(amount)']?result[4][0]['sum(amount)']*conf.yongjin:0)}）`,{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:[
                        [{text:"查看团队",callback_data:"cktd"}]
                    ]
                }
            });
        });
    });

}
function dailizhongxinstart(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*) FROM users where inviter_telegramid = '${msg.from.id}' ;SELECT count(*) FROM users where inviter_telegramid = '${msg.from.id}' and lastchat_time like '${moment().format("YYYY-MM")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}';
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}' and time like '${moment().format("YYYY-MM-DD")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${msg.from.id}' and time like '${moment().format("YYYY-MM")}%' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>邀请好友前来游戏,永久享受${conf.yongjin*100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${msg.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)']?result[0][0]['count(*)']:0)}人（活跃：${(result[1][0]['count(*)']?result[1][0]['count(*)']:0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)']?result[2][0]['sum(amount)']*conf.yongjin:0)}（当日：${(result[3][0]['sum(amount)']?result[3][0]['sum(amount)']*conf.yongjin:0)}    当月：${(result[4][0]['sum(amount)']?result[4][0]['sum(amount)']*conf.yongjin:0)}）`,{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:[
                        [{text:"查看团队",callback_data:"cktd"}]
                    ]
                }
            })
            .then(res=>{
                bot.sendMessage(msg.chat.id,`<b>✅已开启键盘</b>`,{
                    parse_mode:"HTML",
                    reply_markup: {
                        keyboard: conf.keyboard
                    }
                })
            })
        });
    });

}

function backdaili(callbackQuery) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT count(*) FROM users where inviter_telegramid = '${callbackQuery.from.id}' ;SELECT count(*) FROM users where inviter_telegramid = '${callbackQuery.from.id}' and lastchat_time like '${moment().format("YYYY-MM")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${callbackQuery.from.id}';
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${callbackQuery.from.id}' and time like '${moment().format("YYYY-MM-DD")}%' ;
        SELECT sum(amount) FROM bet where type = "${conf.type}" and inviter_telegramid = '${callbackQuery.from.id}' and time like '${moment().format("YYYY-MM")}%' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.editMessageText(`<b>邀请好友前来游戏,永久享受${conf.yongjin*100}%流水分红！</b>\n\n邀请链接：<code>${conf.botusername}?start=${callbackQuery.from.id}</code>\n\n您已邀请：${(result[0][0]['count(*)']?result[0][0]['count(*)']:0)}人（活跃：${(result[1][0]['count(*)']?result[1][0]['count(*)']:0)}人）\n\n累计发放佣金：${(result[2][0]['sum(amount)']?result[2][0]['sum(amount)']*conf.yongjin:0)}（当日：${(result[3][0]['sum(amount)']?result[3][0]['sum(amount)']*conf.yongjin:0)}    当月：${(result[4][0]['sum(amount)']?result[4][0]['sum(amount)']*conf.yongjin:0)}）`,{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
                chat_id:callbackQuery.message.chat.id,
                message_id:callbackQuery.message.message_id,
                reply_markup:{
                    inline_keyboard:[
                        [{text:"查看团队",callback_data:"cktd"}]
                    ]
                }
            });
        });
    });

}
function address(msg) {
	conf.pool.getConnection(function(err, connection) {
		if (err) return err;
		connection.query(`update users set trx_address = "${msg.text}" where telegramid = "${msg.from.id}";`,(error, result)=> {
			if (error) return error;
			connection.destroy();
			bot.sendMessage(msg.chat.id, `✅设置成功\n\n提佣地址：<code>${msg.text}</code>`,{
				parse_mode: 'HTML',
				disable_web_page_preview:true,
				reply_to_message_id:msg.message_id,
			});
		});
	})

}

function chongzhi(msg) {
    bot.sendMessage(msg.chat.id, `<a href="https://t.me/+DYsIFImeDB8xNTQ1">立即加入上下分群</a>`,{
		parse_mode: 'HTML',
		disable_web_page_preview:true,
	});
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`update users set privatetype = "cz"  where telegramid = '${msg.from.id}' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>▶️请输入您要充值的正整数金额，如：5000\n🔺请注意，充值最小金额为30</b>`,{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
            });
        });
    });

}

function tixian(msg) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`select * from users where telegramid = '${msg.from.id}' ;update users set privatetype = "tx"  where telegramid = '${msg.from.id}' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            bot.sendMessage(msg.chat.id, `<b>点击下方按钮，立即提现</b>\n\n佣金余额：<code>${result[0][0].yongjinbalance}元</code>`,{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:conf.yongjintixian_line_keyboard
                }
            });
        });
    });
}

function shuzi(msg) {
    return
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = '${msg.from.id}' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            if (result[0].privatetype=="cz") {
                if (conf.czMin>parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id,`请输入不小于${conf.czMin}的正整数金额！`)
                    return
                }
                conf.pool.getConnection(function(err, connection) {
                    if (err) return err;
                    connection.query(`SELECT * FROM pay where telegramid = '${msg.from.id}' and state = 0;`,(error, result)=> {
                        if (error) return error;
                        connection.destroy();
                        if (result[0]) {
                            bot.sendMessage(msg.from.id, `<b>您还有未完成的充值订单！</b>\n\n此订单10分钟内有效，过期后请重新生成订单。\n➖➖➖➖➖➖➖➖➖➖\n转账地址: <code>${conf.czaddress}</code> (TRC-20网络)\n转账金额: <code>${result[0].amount}</code> USDT\n➖➖➖➖➖➖➖➖➖➖\n请使用绑定的 请等待1分钟左右查询，自动到账。`,{
                                parse_mode: 'HTML',
                                reply_markup: {
                                    inline_keyboard: [[{text:"❎ 取消订单",callback_data:"qxorder"}]]
                                },
                            })
                        }else{
                            var czjine = (parseInt(msg.text) + (Math.random() * (100 - 1) + 1)/1000).toFixed(3)
                            bot.sendMessage(msg.from.id, `<b>此订单10分钟内有效，过期后请重新生成订单。</b>\n➖➖➖➖➖➖➖➖➖➖\n转账地址: <code>${conf.czaddress}</code> (TRC-20网络)\n转账金额: <code>${czjine}</code> USDT\n➖➖➖➖➖➖➖➖➖➖\n请使用绑定的 请等待1分钟左右查询，自动到账。`,{
                                parse_mode: 'HTML',
                                reply_markup: {
                                    inline_keyboard: [[{text:"❎ 取消订单",callback_data:"qxorder"}]]
                                },
                            }).then(res=>{
                                conf.pool.getConnection(function(err, connection) {
                                    if (err) return err;
                                    connection.query(`Insert into pay (name,username,telegramid,amount,state,way,applytime,applytimestamp,replyMessageid) values ("${utf16toEntities((msg.from.first_name?msg.from.first_name:"")+(msg.from.last_name?msg.from.last_name:""))}","${msg.from.username}","${msg.from.id}",${czjine},0,"USDT自动充值",now(),unix_timestamp(),${res.message_id});`,(error, result)=> {
                                        connection.destroy();
                                        if (error) return error;

                                    });
                                })
                            })

                        }
                    });
                });


            }else if(result[0].privatetype=="tx"){
                if (conf.txMin>parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id,`<b>❌请输入不小于${conf.txMin}的正整数金额！</b>`,{
                        parse_mode:"HTML"
                    })
                    return
                }else if (result[0].yongjinbalance<parseInt(msg.text)) {
                    bot.sendMessage(msg.chat.id,`<b>❌佣金余额不足，无法发起提现！</b>`,{
                        parse_mode:"HTML"
                    })
                    return
                }else if (result[0].trx_address=="暂未绑定") {
                    bot.sendMessage(msg.chat.id,`<b>❌暂未设置提现地址，请发送TRC20地址进行绑定！</b>`,{
                        parse_mode:"HTML"
                    })
                    return
                }else{
                    var trx_address = result[0].trx_address;
                    var txamount = (parseFloat(msg.text)*(1-conf.txfee)/conf.utormb).toFixed(2)
                    transferUSDT(result[0].trx_address,txamount)
                    .then(res=>{
                        conf.pool.getConnection(function(err, connection) {
                            if (err) return err;
                            connection.query(`Insert into withdrawal (name,telegramid,amount,state,way,applytime,changetime,replyMessageid,hashid,trx_address) values ("${msg.from.username}","${msg.from.id}",${msg.text},1,"USDT",now(),now(),${msg.message_id},"${hashid}","${trx_address}");update users set balance = balance-${msg.text} where telegramid = "${msg.from.id}";`,(error, result)=> {
                                connection.destroy();
                                if (error) return error;
                                bot.sendMessage(msg.from.id, `<b>✅${txamount}USDT提现成功，请注意查收~</b>`,{
                                    parse_mode: 'HTML',
                                    reply_markup:{
                                        inline_keyboard:[
                                            [{text:"查看详情",url:`https://tronscan.org/#/transaction/${hashid}`}]
                                        ]
                                    }
                                })
                            });
                        })
                    })
                    .catch((error) => {
                        bot.sendMessage(msg.from.id, `<b>❌提现失败，请联系管理员处理！</b>`,{
                            parse_mode: 'HTML',
                        })
                    })
                }
            }
        });
    });
}

function quanbutixian(telegramid,chatid,messageid,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = '${telegramid}' ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            if (conf.txMin>result[0].yongjinbalance) {
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `❌提现失败，未达到最低提现金额(${conf.txMin})！`,
                    show_alert:true,
                    cache_time:1
                })
                return
            }else if (result[0].trx_address=="暂未绑定") {
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `❌请先设置提现地址,发送地址即可自动绑定！`,
                    show_alert:true,
                    cache_time:1
                })
                return
            }else{
                return
                var trx_address = result[0].trx_address;
                var txamount = (result[0].yongjinbalance*(1-conf.txfee)/conf.utormb).toFixed(2)
                transferUSDT(result[0].trx_address,txamount)
                .then(res=>{
                    conf.pool.getConnection(function(err, connection) {
                        if (err) return err;
                        connection.query(`Insert into withdrawal (name,telegramid,amount,state,way,applytime,changetime,replyMessageid,hashid,trx_address) values ("${msg.from.username}","${msg.from.id}",${msg.text},1,"USDT",now(),now(),${msg.message_id},"${hashid}","${trx_address}");update users set balance = balance-${msg.text} where telegramid = "${msg.from.id}";`,(error, result)=> {
                            connection.destroy();
                            if (error) return error;
                            bot.editMessageText(`<b>✅${txamount}USDT提现成功，请注意查收~</b>`,{
                                chat_id:chatid,
                                message_id:messageid,
                                parse_mode: 'HTML',
                                reply_markup:{
                                    inline_keyboard:[
                                        [{text:"查看详情",url:`https://tronscan.org/#/transaction/${hashid}`}]
                                    ]
                                }
                            })
                        });
                    })
                })
                .catch((error) => {
                    bot.answerCallbackQuery(callbackQueryid,{
                        text: `❌提现失败，请联系管理员处理！`,
                        show_alert:true,
                        cache_time:1
                    })
                })
            }
        });
    });
}

function privatemain(msg) {

    if (msg.text.split(" ")[1]=="dlzx") {
        dailizhongxinstart(msg)
    }else if(msg.text.split(" ")[1]=="yxgz") {
        guizehuodong(msg)
    }else if(msg.text.split(" ")[1]=="fl") {
        fuli(msg)
    }else if(msg.text=="🏠代理中心"){
        dailizhongxin(msg)
    }else if(msg.text.search("/start")==0) {
        start(msg)
    }else if(tronWeb.isAddress(msg.text)){
        address(msg)
    }else if(msg.text=="游戏规则"){
        guizehuodong(msg)
    }else if(msg.text=="开始游戏"){
        kaishiyouxi(msg)
    }else if(msg.text=="最近投注"){
        zuijintouzhu(msg)
    }else if(msg.text=="账单记录"){
        zhangdanjilu(msg)
    }else if(msg.text=="个人中心"){
        usercenter(msg)
    }else if(msg.text=="我要充值"){
        chongzhi(msg)
    }else if(msg.text=="🏧佣金提现"){
        tixian(msg)
    }else if(parseInt(msg.text)%1==0){
        shuzi(msg);
    }
}
/*主函数，处理过滤完的文字消息 */
function main(msg) {
    if (!isfengpan) {
        var nickname = guolvname((msg.from.first_name? msg.from.first_name:"")+( msg.from.last_name? msg.from.last_name:""))
        if(msg.text=="取消" || msg.text=="撤回"){
            quanbuchehui(msg.text,msg.from.id,msg.from.username,msg.message_id)
        }else if(msg.text.search("历史")!=-1){
            lishichaxun(msg.text,msg.from.id,msg.from.username,msg.message_id)
        }else if(msg.text=="2"){
            lishi(msg.text,msg.from.id,msg.from.username,msg.message_id)
        }else if(msg.text=="1" || msg.text=="余额"){
            benqitouzhutxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id,nickname)
        }else if(msg.text=="反水"){
            getReturnWatertxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id)
        }else{
            bet(msg.text,msg.from.id,msg.from.username,msg.message_id,nickname);
        }
    }
}

function shangfenadmin(contant,telegramid,name,replyMessageid,username,fromusername,replyFromMessageid) {
    if (parseInt(contant.split('+')[1])%1==0 && contant.split('+')[0]=="" && !isNaN(Number(contant.split("+")[1],10))) {

        conf.pool.getConnection(function(err, connection) {
            if (err) {
                return err;
            }
            connection.query(`SELECT * FROM users where telegramid = "${telegramid}";SELECT sum(amount) FROM pay where telegramid = "${telegramid}" and applytime > "${moment(Math.round(date)-1000*60*60*24*7).format("YYYY-MM-DD HH:mm:ss")}";`,(error, result)=> {
                if (error) return error;
                if (result[0][0]) {
                    var balance = result[0][0].balance;
                    var shangfensql = ""
                    if (balance<=10) {
                        shangfensql =  `update users set balance  = balance + ${contant.split("+")[1]},todaychongzhi = todaychongzhi + ${contant.split("+")[1]},chongzhiamount = ${contant.split("+")[1]},liushui = 0,lastpay_time = now() where telegramid = "${telegramid}";`
                    }else{
                        shangfensql =  `update users set balance  = balance + ${contant.split("+")[1]},todaychongzhi = todaychongzhi + ${contant.split("+")[1]},chongzhiamount = chongzhiamount +${contant.split("+")[1]},lastpay_time = now() where telegramid = "${telegramid}";`
                    }

                    console.log(shangfensql)
                    connection.query(`select * from users where telegramid = "${result[0][0].inviter_telegramid}"; `,(error, r)=> {
                        console.log(error)
                        if (error) return error;
                        connection.query(`${shangfensql}Insert into pay (telegramid,amount,state,way,applytime,replyMessageid) values ("${telegramid}",${contant.split("+")[1]},1,"群内管理上分",now(),${replyMessageid});`,(error, result)=> {
                            connection.destroy();
                            console.log(error)

                            if (error) return error;
                            bot.sendMessage(conf.houtaiqunid, `✅充值成功\n\n账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a> \n上分：<code>${contant.split("+")[1]}</code>\n余额：<code>${(balance+parseFloat(contant.split("+")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`,{
                                parse_mode:"HTML"
                            })
                            bot.sendMessage(conf.chatid, `<b>📣<code>${name}</code>充值的 ${contant.split("+")[1]}RMB 已到账！</b>`,{
                                parse_mode:"HTML"
                            })
                            console.log('replyFromMessageid====',replyFromMessageid)
                            bot.sendPhoto(conf.sxfqunid,'./img/shangfen.jpg',{
                                parse_mode: 'HTML',
                                disable_web_page_preview:true,
                                reply_to_message_id: replyMessageid,
                                caption:`${name}老板成功上分: ${contant.split("+")[1]} 元 \n➖➖➖➖➖➖➖➖➖➖\n♦️ 余额: ${(balance+parseFloat(contant.split("+")[1]))} 元\n恒旺集团上分模式📣\n支持🔥支付宝微信银行卡 💰\n支持🔥 USDT上分\n支持🔥福利来钱包上分  @ndjd7375`
                            })

                            console.log('date===============',date)
                            // if (date.getHours()!==19) {
                                bot.sendMessage(conf.jndqunid, `<b>📣<code>${name}</code>充值的 ${contant.split("+")[1]}RMB 已到账！</b>`,{
                                    parse_mode:"HTML"
                                })
                            // }
                        });
                    });


                }else{
                    connection.destroy();
                }
            });
        })
    }
}


function qiandao(contant,telegramid,name,replyMessageid,fromid,chatid) {
    var sql = ""
    for (let index = 0; index < 7; index++) {
        sql += `select sum(amount) from pay where applytime like "${getlastday(index+1)}" and state = 1 and telegramid = "${telegramid}"; `
    }
    conf.pool.getConnection(function(err, connection) {
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";${sql}select count(*) from bet where type = "${conf.type}" and telegramid = "${telegramid}" and result is not null and time like "${moment(Math.round(new Date)-1*60*60*24*1000).format("YYYY-MM-DD%")}" and amount >= 10; `,(error, result)=> {
            if (error) throw error;
            if (!result[0][0]) {
                return
            }
            var zengsongjine = getqiandao(result)
            if (zengsongjine>0 && result[8][0]['count(*)'] && result[0][0]['lastqiandao_time'].search(moment().format("YYYY-MM-DD"))==-1) {
                var balance = result[0][0].balance;
                /*if (zengsongjine==56 && result[0][0].qiandaoamount==7) {
                    zengsongjine = 6;
                }*/

                connection.query(`Insert into jiangli (telegramid,amount,type,time) values ("${telegramid}",${zengsongjine},"签到奖励",now()); update users set balance  = balance + ${zengsongjine}, lastqiandao_time = now(),chongzhiamount = chongzhiamount + ${zengsongjine} where telegramid = "${telegramid}"`,(error, result)=> {
                    connection.destroy();
                    console.log(error);
                    if (error) throw error;
                    bot.sendMessage(conf.houtaiqunid, `用户ID：<code>${telegramid}</code>\n用户名：<code>${name}</code> \n余额：<code>${balance}元</code>\n赠送签到奖励：<code>${zengsongjine}</code>`,{
                        parse_mode:"HTML"
                    })
                    bot.sendMessage(chatid, `<b>📣<code>${name}</code>的签到奖励 ${zengsongjine} ,已成功到账！</b>`,{
                        parse_mode:"HTML"
                    })
                });
            }else if (zengsongjine==0){
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)未满足充值条件，无法领取签到奖励</b>`,{
                    parse_mode:"HTML"
                })
            }else if(result[8][0]['count(*)']+result[9][0]['count(*)']+result[10][0]['count(*)']<10){
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)未满足当日投注条件，无法领取签到奖励</b>`,{
                    parse_mode:"HTML"
                })
            }else if(result[0][0]['lastqiandao_time'].search(moment().format("YYYY-MM-DD")!=-1)){
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)今日已领取签到奖励，无法再次领取</b>`,{
                    parse_mode:"HTML"
                })
            }else{
                connection.destroy();
                bot.sendMessage(chatid, `<b>❌<code>${name}</code>(<code>${telegramid}</code>)不符合赠送条件，无法领取签到奖励</b>`,{
                    parse_mode:"HTML"
                })
            }
        });
    })
}

function getqiandao(result) {
    var fafangamount = 0
    console.log(result);
    for (let index = 1; index < result.length; index++) {
        if(result[index][0]['sum(amount)']>500){
            if (index==1) {
                fafangamount = fafangamount+ 6
            }else if (index==2) {
                fafangamount = fafangamount+ 6
            }else if (index==3) {
                fafangamount = fafangamount+ 6
            }else if (index==4) {
                fafangamount = fafangamount+ 10
            }else if (index==5) {
                fafangamount = fafangamount+ 10
            }else if (index==6) {
                fafangamount = fafangamount+ 10
            }else if (index==7) {
                fafangamount = fafangamount+ 10
            }
        }else{
            return fafangamount
        }
    }
    return fafangamount
}


function yongjintixian(contant,telegramid,name,replyMessageid,username,fromusername,chatid) {
    if (parseInt(contant.split('yj')[1])%1==0 && contant.split('yj')[0]=="" && !isNaN(Number(contant.split("yj")[1],10))) {
        conf.pool.getConnection(function(err, connection) {
            connection.query(`SELECT * FROM users where telegramid = "${telegramid}";`,(error, result)=> {
                if (error) return error;
                if (result.length==0) {
                    connection.destroy();
                    bot.sendMessage(conf.sxfqunid, `<b>❌佣金余额不足，提现发起失败！</b>`,{
                        parse_mode:"HTML"
                    })
                    .then(res=>{
                        setTimeout(function (params) {
                            bot.deleteMessage(conf.sxfqunid,res.message_id)
                        },180000)
                    })
                }else{

                    var userinfo = result[0];
                    if(userinfo.yongjinbalance<parseFloat(contant.split("yj")[1])){
                        connection.destroy();
                        bot.sendMessage(conf.sxfqunid, `<b>❌当前可提现佣金 ${userinfo.yongjinbalance}，提现发起失败！</b>`,{
                            parse_mode:"HTML"
                        })
                        .then(res=>{
                            setTimeout(function (params) {
                                bot.deleteMessage(conf.sxfqunid,res.message_id)
                            },180000)
                        })
                    }else{
                        connection.query(`select * from users where telegramid = "${userinfo.inviter_telegramid}";update users set yongjinbalance  = yongjinbalance - ${contant.split("yj")[1]} where telegramid = "${telegramid}"`,(error, result)=> {
                            connection.destroy();
                            if (error) return error;
                            console.log('=========',error)
                            bot.sendMessage(-932657331, `✅佣金提现成功\n\n${(result[0][0]?`上级：<a href="https://t.me/${result[0][0].name}">${result[0][0].nickname}</a>\n`:"")}账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a>\n佣金：<code>${contant.split("yj")[1]}</code>\n余额：<code>${(userinfo.yongjinbalance-parseFloat(contant.split("yj")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`,{
                                parse_mode:"HTML"
                            })
                            bot.sendMessage(conf.chatid, `<b>💎代理 <code>${name}</code>,${contant.split("yj")[1]}请查收！</b>`,{
                                parse_mode:"HTML"
                            })
                        });
                    }

                }
            });
        })
    }
}

function xiafenadmin(contant,telegramid,name,replyMessageid,username,fromusername,chatid) {
    if (parseInt(contant.split('-')[1])%1==0 && contant.split('-')[0]=="" && !isNaN(Number(contant.split("-")[1],10))) {
        conf.pool.getConnection(function(err, connection) {
            connection.query(`SELECT * FROM users where telegramid = "${telegramid}";`,(error, result)=> {
                if (error) return error;
                if (result.length==0) {
                    connection.destroy();
                    bot.sendMessage(conf.sxfqunid, `<b>❌余额不足，提现发起失败！</b>`,{
                        parse_mode:"HTML"
                    })
                    .then(res=>{
                        setTimeout(function (params) {
                            bot.deleteMessage(conf.sxfqunid,res.message_id)
                        },180000)
                    })
                }else{
                    var userinfo = result[0];
                    connection.query(`select sum(amount) from bet where type = "${conf.type}" and telegramid = "${telegramid}" and time > "${userinfo.lastpay_time}" and result is not NULL ;`,(error, result)=> {
                        if (error) return error;
                        if(userinfo.balance<parseFloat(contant.split("-")[1])){
                            connection.destroy();
                            bot.sendMessage(conf.sxfqunid, `<b>❌当前可提现余额 ${userinfo.balance}，提现发起失败！</b>`,{
                                parse_mode:"HTML"
                            })
                            .then(res=>{
                                setTimeout(function (params) {
                                    bot.deleteMessage(conf.sxfqunid,res.message_id)
                                },180000)
                            })
                        }else if(userinfo.liushui<userinfo.chongzhiamount*conf.shui) {
                            connection.destroy();
                            bot.sendMessage(conf.sxfqunid, `<b>❌当前流水${userinfo.liushui}，需大于 ${userinfo.chongzhiamount*conf.shui} 后，方可提现!</b>`,{
                                parse_mode:"HTML"
                            })
                            .then(res=>{
                                setTimeout(function (params) {
                                    bot.deleteMessage(conf.sxfqunid,res.message_id)
                                },180000)
                            })
                            return
                        }else{
                            connection.query(`Insert into withdrawal (telegramid,amount,state,way,applytime,replyMessageid) values ("${telegramid}",${contant.split("-")[1]},1,"群内管理下分",now(),${replyMessageid}); update users set balance  = balance - ${contant.split("-")[1]},chongzhiamount = 0,liushui = 0 where telegramid = "${telegramid}"`,(error, result)=> {
                                connection.destroy();
                                if (error) return error;
                                bot.sendMessage(conf.houtaiqunid, `✅提现成功\n\n账号：<code>${telegramid}</code>\n昵称：<a href="https://t.me/${username}">${name}</a>\n下分：<code>${contant.split("-")[1]}</code>\n余额：<code>${(userinfo.balance-parseFloat(contant.split("-")[1]))}元</code>\n\n操作：<code>${fromusername}</code>\n时间：<code>${moment().format("YYYY-MM-DD HH:mm:ss")}</code>`,{
                                    parse_mode:"HTML"
                                })
                                bot.sendMessage(conf.chatid, `<b>💎贵宾 <code>${name}</code>,${contant.split("-")[1]}请查收！</b>`,{
                                    parse_mode:"HTML"
                                })
                            });
                        }
                    });

                }
            });
        })
    }
}

function checkarray(item,array) {

    for (let index = 0; index < array.length; index++) {
        if (array[index]==item) {
            return true
        }

    }
    return false;
  }

function sxf(msg) {
    if(msg.text.search("上分")!=-1){
        shangfen(msg.text,msg.from.id,msg.from.username,msg.message_id)
    }else if(msg.text.search("下分")!=-1){
        xiafen(msg.text,msg.from.id,msg.from.username,msg.message_id)
    }else if(msg.text=="1"){
        yuetxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id)
    }else if(msg.text.search("/zjtz")!=-1){
        getMyBettxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id)
    }else if(msg.text.search("/ckls")!=-1){
        getTodayBilltxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id)
    }else if(msg.text.search("/lqfs")!=-1){
        getReturnWatertxt(msg.text,msg.from.id,msg.from.username,msg.message_id,msg.chat.id)
    }
}

/*上分*/
function shangfen(contant,telegramid,name,replyMessageid) {
    bot.sendMessage(conf.sxfqunid, `人民币上下分•100元起
USDT上下分•15U起

🔥上分支持-微信-支付宝-银行卡-USDT

充值上分找客服：@ndjd7375

⚠️认准客服ID，主动私聊你一定是骗子！

转账后私发截图给客服，通过审核后会第一时间上分。

🌟USDT上分地址:

<code>TWkKrQTmqJ2ophpefUiWV3WqxdXz6Ahqhd</code>

点击U地址（自动复制）
认准U地址：ws21s3g结尾

⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！
⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！
⚠️注意：客服不会主动私聊你，主动私聊你的一定是骗子！！！`,{
        reply_to_message_id: replyMessageid,
        parse_mode: 'HTML',
        reply_markup:{
            inline_keyboard:conf.tixian_inline_keyboard
        },
        disable_web_page_preview:true
    })
}

/*下分*/
function xiafen(contant,telegramid,name,replyMessageid) {
    return
    if (parseInt(contant.split('下分')[1])%1==0 && contant.split('下分')[0]=="" && !isNaN(Number(contant.split("下分")[1],10))) {
        conf.pool.getConnection(function(err, connection) {
            connection.query(`SELECT * FROM users where telegramid = "${telegramid}";SELECT SUM(amount) FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and resultid = "${resultid}";`,(error, result)=> {
                if (error) return error;
                if (result.length==0) {
                    bot.sendMessage(conf.sxfqunid, `余额不足，提现失败！`,{
                        reply_to_message_id: replyMessageid
                    })
                }else{
                    var balance = result[0][0].balance;
                    if(balance>=parseFloat(contant.split("下分")[1])){
                        connection.query(`Insert into withdrawal (name,telegramid,amount,state,way,applytime,replyMessageid) values ("${name}","${telegramid}",${contant.split("下分")[1]},0,"群内下分",now(),${replyMessageid}); update users set balance  = balance - ${contant.split("下分")[1]} where telegramid = "${telegramid}"`,(error, result)=> {
                            connection.destroy();
                            if (error) return error;
                            bot.sendMessage(conf.sxfqunid, `账号:${telegramid}\n用户名：${name} \n余额：${(balance-parseFloat(contant.split("下分")[1])).toFixed(2)}元\n您的下分申请提交成功，请勿重复提交，审核通过后第一时间下分`,{
                                reply_to_message_id: replyMessageid
                            })
                        });
                    }else{
                        bot.sendMessage(conf.sxfqunid, `余额不足，提现失败！`,{
                            reply_to_message_id: replyMessageid
                        })
                    }
                }
            });
        })
    }
}
/*发送即将封盘提醒*/
function fengpantixing() {
    bot.sendMessage(conf.chatid, `<b>⏰封盘提醒 :\n\n<code>${resultid}</code>期距离封盘还剩40秒！</b>`,{
        parse_mode:"HTML"
    })
    .then(res=>{
        fengpancishu++
    })
    .catch(err=>{
        console.log(err);

    })
}



/*查询开奖历史*/
function lishichaxun(contant,telegramid,name,replyMessageid) {
    if (parseInt(contant.split('历史')[1])%1!=0  || parseInt(contant.split('历史')[1])<0 || isNaN(Number(contant.split("历史")[1],10))) {
       return
    }
    var qishu = 0;
    if (parseInt(contant.split('历史')[1])>50) {
        qishu = 10
    }else{
        qishu = parseInt(contant.split('历史')[1])
    }
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM result WHERE type = "${conf.type}" ORDER by result_time desc limit ${qishu} ;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var historylist = "";
            for (let index = 0; index < result.length; index++) {
                historylist = `${historylist}<b>${result[index].id}</b>期  ${result[index].one} ${result[index].two} ${result[index].three} = ${(result[index].one+result[index].two+result[index].three)>=10?(result[index].one+result[index].two+result[index].three):"0"+(result[index].one+result[index].two+result[index].three)}\n`;
            }
            bot.sendMessage(conf.chatid, `<code>------ 历史开奖 -----</code>\n${historylist}<code>---------------------------</code>`,{
                reply_to_message_id: replyMessageid,
                parse_mode:"HTML"
            })
        });
    });
}


/*查询开奖历史*/
function lishi(contant,telegramid,name,replyMessageid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM result where type = "${conf.type}" and three is not null ORDER by result_time desc limit 10;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var historylist = "";
            for (let index = 0; index < result.length; index++) {
                historylist = `${historylist}<b>${result[index].id}</b>期  ${result[index].one} ${result[index].two} ${result[index].three} = ${(result[index].one+result[index].two+result[index].three)>=10?(result[index].one+result[index].two+result[index].three):"0"+(result[index].one+result[index].two+result[index].three)}\n`;
            }
            bot.sendMessage(conf.chatid, `<code>------ 历史开奖 -----</code>\n${historylist}<code>---------------------------</code>`,{
                reply_to_message_id: replyMessageid,
                parse_mode:"HTML"
            })
        });
    });
}

/*取消单个*/
function chehui(contant,telegramid,name,replyMessageid,message_thread_id) {
    if (isfengpan) {
        bot.sendMessage(conf.chatid, `取消失败！\n原因:已经封盘`,{
            reply_to_message_id: replyMessageid
        })
        return
    }
    if (!message_thread_id) {
        bot.sendMessage(conf.chatid, `无法获取消息的回复id，请使用“全部取消”功能！`,{
            reply_to_message_id: replyMessageid
        })
        return
    }
    var chehuisql = "";
    var chehuiorder = "";
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and messageid = "${message_thread_id}" and telegramid = "${telegramid}" and resultid = "${resultid}";`,(error, result)=> {
            if (error) return error;
            for (let index = 0; index < result.length; index++) {
                chehuiorder = `${chehuiorder}${result[index].guess}-${result[index].amount}\n`
                chehuisql =  `${chehuisql}DELETE FROM bet  where type = "${conf.type}" and id  ='${result[index].id}';UPDATE users set balance = balance + ${result[index].amount} where telegramid = "${result[index].telegramid}"; `
            }
            if (result.length==0) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `取消失败！\n原因:已经开奖`,{
                    reply_to_message_id: replyMessageid
                })
            } else {
                connection.query(chehuisql,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(conf.chatid, `取消成功！\n包含的投注有：\n${chehuiorder}`,{
                        reply_to_message_id: replyMessageid
                    })
                });
            }

        });
    });
}

/*文字消息查看余额*/
function yuetxt(contant,telegramid,name,replyMessageid,chatid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            if (result[0]) {
                var txstate = ""
                if (result[0].liushui>=result[0].chongzhiamount*conf.shui) {
                    txstate = "✅已满足提现条件"
                }else{
                    txstate = "❌流水未达标，不可提现"
                }
                bot.sendMessage(chatid, `<b>用户信息</b>\n账号：<code>${result[0].telegramid}</code>\n昵称：<code>${entitiestoUtf16(result[0].nickname)}</code>\n余额：<code>${result[0].balance}</code>元\n佣金：<code>${result[0].yongjinbalance}</code>\n\n<b>流水检测</b>\n流水：<code>${result[0].liushui}</code>\n${txstate}`,{
                    reply_to_message_id: replyMessageid,
                    parse_mode:"HTML",
                    reply_markup: {
                        inline_keyboard: conf.tixian_inline_keyboard
                    },
                })
                .then(res=>{
                    setTimeout(function (params) {
                        bot.deleteMessage(res.chat.id,res.message_id)
                    },180000)
                })
            }
        });
    });

}


/*文字消息查看余额*/
function benqitouzhutxt(contant,telegramid,name,replyMessageid,chatid,firstname) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";select * from bet where type = "${conf.type}" and  telegramid = "${telegramid}"  and result is null;`,(error, result)=> {
        console.log('sql===========',`select * from bet where type = "${conf.type}" and  telegramid = "${telegramid}" and result is null;`)
            connection.destroy();
            if (error) return error;
            if (result[0].length==0) {
                bot.sendMessage(chatid, `👤${firstname}   \n💰余额：0.00元`,{
                    reply_to_message_id: replyMessageid
                })
            } else if(!result[1][0]){
                bot.sendMessage(chatid, `<b>暂无可发🎲的投注</b>\n\n👤${firstname}   \n💰余额：${(result[0][0].balance)}元`,{
                    reply_to_message_id: replyMessageid,
                    parse_mode:"HTML"
                })
            } else{
				var quanbutouzhu = "";
                for(var index = 0;index<result[1].length;index++){
					quanbutouzhu += `<code>${result[1][index].guess}</code>-<code>${result[1][index].amount}</code>(<code>${result[1][index].peilv}</code>倍赔率)\n`
				}
				bot.sendMessage(conf.chatid, `投注完成后可直接发送<code>🎲</code>进行手摇\n在300秒之内必须手摇完成，否则将会过期不退款\n➖➖➖➖➖➖➖➖➖➖\n您的全部投注：\n${quanbutouzhu}➖➖➖➖➖➖➖➖➖➖\n👤${firstname}  \n💰余额：${(result[0][0].balance)}元`,{
					reply_to_message_id: replyMessageid,
					parse_mode:"HTML"
				})
            }
        });

    });

}

/*文字消息查询我的投注记录*/
function getMyBettxt(contant,telegramid,name,replyMessageid,chatid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = '${telegramid}' order by id desc LIMIT 10;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (result[index].resultid==resultid) {
                    result_money = `待开奖`
                }else if (result[index].result == 0) {
                    result_money = `未中奖`
                }else{
                    result_money = `中奖${result[index].result.toFixed(2)}${conf.coin[0]}`
                }
                myBet = `${myBet} ${result[index].resultid}期：${result[index].guess}${result[index].amount.toFixed(2)}${conf.coin[0]}-${result_money}\n`;
            }
            bot.sendMessage(chatid, `最近投注记录：\n${myBet}`,{
                reply_to_message_id: replyMessageid
            })
        });
    });
}

/*文字消息查询流水*/
function getTodayBilltxt(contant,telegramid,name,replyMessageid,chatid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and time LIKE CONCAT(CURDATE(), '%');`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var todayWin = 0;
            var todayPurchase = 0;
            var todayWaitResult = 0;
            for (let index = 0; index < result.length; index++) {
                if (resultid!=result[index].resultid) {
                    todayWin = todayWin+result[index].result-result[index].amount+result[index].amountreturn;
                    todayPurchase = todayPurchase + result[index].amount;
                }else{
                    todayWaitResult = todayWaitResult + result[index].amount;
                }
            }
            bot.sendMessage(chatid, `待结算：${todayWaitResult.toFixed(2)} ${conf.coin}\n今日输赢：${todayWin.toFixed(2)} ${conf.coin}\n今日总流水：${todayPurchase.toFixed(2)} ${conf.coin}`,{
                reply_to_message_id: replyMessageid
            })
        });
    });
}

/*文字消息领取反水*/
function getReturnWatertxt(contant,telegramid,name,replyMessageid,chatid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and isreturn = 0 and resultid != ${resultid};`,(error, result)=> {
            if (error) return error;
            var myReturnWater = 0;
            for (let index = 0; index < result.length; index++) {
                myReturnWater = myReturnWater + result[index].amount*conf.returnWater;
            }
            if (parseInt(myReturnWater)<1) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `<b>❌可领取反水小于1，无法领取</b>`,{
                    reply_to_message_id: replyMessageid,
                    parse_mode:"HTML"
                })
                return
            }else{
                connection.query(`select * from users where telegramid = "${telegramid}";UPDATE users set balance = balance + ${parseInt(myReturnWater)} where telegramid = "${telegramid}";UPDATE bet set isreturn = 1,amountreturn = amount*${conf.returnWater} where type = "${conf.type}" and telegramid = "${telegramid}" and resultid != "${resultid}";`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(chatid, `<b>流水金额：<code>${parseInt(myReturnWater/conf.returnWater)}</code>\n反水比例：<code>${conf.returnWater*100}%</code>\n反水金额：<code>${parseInt(myReturnWater)}</code> \n\n当前余额：<code>${(result[0][0].balance+parseInt(myReturnWater))}元</code></b>`,{
                        reply_to_message_id: replyMessageid,
                        parse_mode:"HTML"
                    })

                });
            }

        });
    });
}

function guolvname(name) {
    var namestr = name.substring(0,10);
    var newname = ""
    var wjz = ["$","<",">","{","}","\""]
    for (let index = 0; index < namestr.length; index++) {
        var iswjz = false
        for (let a = 0; a < wjz.length; a++) {
            if (namestr[index]==wjz[a]) {
                iswjz = true
            }
        }
        if (!iswjz) {
            newname+=namestr[index]
        }

    }
    return newname
}

/*全部取消*/
function quanbuchehui(contant,telegramid,name,replyMessageid) {
    var chehuisql = "";
    var chehuiorder = "";
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and one is null;`,(error, result)=> {
        console.log('取消========',`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and one is null;`)
            if (error) return error;
            if (result.length==0) {
                connection.destroy();
                bot.sendMessage(conf.chatid, `<b>❌您当期暂无任何投注！</b>`,{
                    reply_to_message_id: replyMessageid,
                    parse_mode:"HTML"
                })
            } else {
                for (let index = 0; index < result.length; index++) {
                    chehuiorder = `${chehuiorder}${result[index].guess}-${result[index].amount}\n`
                    chehuisql =  `${chehuisql}DELETE FROM bet  where type = "${conf.type}" and id  ='${result[index].id}';UPDATE users set balance = balance + ${result[index].amount} where telegramid = "${result[index].telegramid}"; `
                }
                connection.query(chehuisql,(error, rr)=> {
                    connection.destroy();
                    if (error) return error;
                    bot.sendMessage(conf.chatid, `<b>🔙${result[0].resultid}期投注已取消！</b>`,{
                        reply_to_message_id: replyMessageid,
                        parse_mode:"HTML"
                    })
                });
            }
        });
    });

}

/*设置开奖期数*/
function setResultID() {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT COUNT(*) FROM result WHERE type = "${conf.type}" and result_time LIKE CONCAT(CURDATE(), '%');`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            resultid = `${date.getFullYear()}${(date.getMonth()+1<10?"0"+(date.getMonth()+1):date.getMonth()+1)}${(date.getDate()<10?"0"+date.getDate():date.getDate())}${result[0]['COUNT(*)']+1}`;
        });
    });

}

/*查询用户余额*/
function getBalance(telegramid,name,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = '${telegramid}';`,(error, result)=> {
            if (error) return error;
            console.log("yonghuyue",name);
            if (result.length==0) {
                connection.query(`Insert into users (name,telegramid,register_time) values ('${name}','${telegramid}',now());`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                    bot.answerCallbackQuery(callbackQueryid,{
                        text:`余额：0元`,
                        show_alert:true,
                        cache_time:10
                    })
                });
            }else{
                connection.destroy();
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `余额：${result[0].balance}元`,
                    show_alert:true,
                    cache_time:10
                })
            }
        });
    });
}

/*查询我的投注记录*/
function getMyBet(telegramid,name,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = '${telegramid}' and result > 0 order by id desc LIMIT 5;`,(error, result)=> {
            if (error) return error;
            console.log("touzhujilu",name);
            connection.destroy();
            var myBet = "";
            for (let index = 0; index < result.length; index++) {
                if (!result[index].result) {
                    result_money = `⏰`
                }else if (result[index].result == 0) {
                    result_money = `❌`
                }else{
                    result_money = `✅`
                }
                myBet = `${myBet}${result_money} ${result[index].resultid}-${result[index].guess}-${result[index].amount}\n`;
            }
            bot.answerCallbackQuery(callbackQueryid,{
                text: `${myBet}`,
                show_alert:true,
                cache_time:10
            })

        });
    });
}


/*封盘*/
function getAllBet(telegramid) {

    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`update gamestate set state = 1 where game = 'ks';`,(error, result)=> {
            if (error) return error;
            connection.destroy();
        });
    });
    conf.pool.getConnection(function(err, connection) {
		if (err) {
			console.log(err);
			return;
		}
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and resultid = "${resultid}" order by telegramid desc;`,(error, result)=> {
            if (error) {
			    console.log(error);
				return;
			}
            connection.destroy();
            var AllBet = ``;
            for (let index = 0; index < result.length; index++) {
                AllBet = `${AllBet}\n${entitiestoUtf16(result[index].firstname)} <code>${result[index].guess}(${result[index].amount})</code>`;
            }
            if (AllBet.length>900) {
                AllBet = ""
                for (let index = 0; index < 20; index++) {
                    AllBet = `${AllBet}\n${entitiestoUtf16(result[index].firstname)} <code>${result[index].guess}(${result[index].amount})</code>`;
                }
                AllBet += `\n等${result.length}次投注`
            }

            resultArray = result;
            fengpantime = moment(Math.round(date)+120000).format("HH:mm[:50]");
            kaijiangtime = moment(Math.round(date)+145000).format("HH:mm[:00]");
            var fengpanresulttxt = `<b><code>${resultid}</code>期 - 开奖时间 <code>${moment(Math.round(date)+25000).format("HH:mm[:00]")}</code></b>\n<b>— — — — - 封盘线 - — — — —</b>${AllBet}\n\n<b>— 已封盘,线上下注全部有效 —</b>`;
            if (conf.sendmode=="t") {
                bot.sendMessage(conf.chatid, fengpanresulttxt,{
                    parse_mode:"HTML",
                    reply_markup: JSON.stringify({
                        inline_keyboard: conf.inline_keyboard
                    })
                })
                .then(res=>{
                    iskaijiang = false;
                })
                .catch(e=>{
                    console.log(e);
                    iskaijiang = false;
                });
            }else if(conf.sendmode=="pt"){
                bot.sendPhoto(conf.chatid, tzxz,{
                    parse_mode:"HTML",
                    caption:fengpanresulttxt
                })
                .then(res=>{
                    iskaijiang = false;
                })
                .catch(e=>{
                    console.log(e);
                    iskaijiang = false;

                    conf.pool.getConnection(function(err, connection) {
                        if (err) return err;
                        connection.query(`update gamestate set state = 1 where game = 'ks';`,(error, result)=> {
                            if (error) return error;
                            connection.destroy();
                        });
                    });
                });
            }
        });
    });
}

/*下注*/
function bet(contant,telegramid,name,replyMessageid,firstname) {
    console.log('========开始下注===========================')
    var shuzisql = ""
    for (let index = 4; index < 18; index++) {
        shuzisql += `select sum(amount) from bet where type = "${conf.type}" and telegramid = "${telegramid}" and resultid = "${resultid}" and guess ="杀${index}点";`
    }
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        console.log('err====',err)
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";${shuzisql}SELECT COUNT(*) FROM result WHERE type = "${conf.type}" and result_time LIKE CONCAT(CURDATE(), '%');SELECT * FROM bet WHERE type = "${conf.type}" and telegramid = "${telegramid}" and one is null;SELECT * FROM result WHERE type = "${conf.type}" and telegramid = "${telegramid}" and one is not null and three is null and result_time >  "${moment(Math.round(date)-300000).format("YYYY-MM-DD HH:mm:ss")}";`,(error, result)=> {
            console.log('error====',error)
            console.log('result====',result)
            if (error) return error;
            var isnertresultsql = ""
            var resultid = 1
            console.log(!result[16][0]);
            if (!result[16][0]) {
                resultid  = moment(date).format("YYYYMMDD")+(result[15][0]['COUNT(*)'])
                isnertresultsql = `INSERT INTO result (id ,result_time,telegramid,type) VALUES ("${resultid}",now(),"${telegramid}","${conf.type}");`
            }else{
                resultid  = result[16][0].resultid
            }
            console.log('resultid===',resultid);
            if (result[17][0]) {
                bot.sendMessage(conf.chatid,`<b>❌您还有投注未完成，无法继续投注</b>`,{
                    parse_mode:"HTML"
                })
               return
            }
            var userBalance = result[0][0].balance;
            var userinfo = result[0][0];
			var xiazhujine = 0;
            var baozi_xiazhujine = 0;
            var shabaozi_xiazhujine = 0;
            var shuzi_xiazhujine = 0;
            var shuziamount = {
                "杀4点":(result[1][0]['sum(amount)']?result[1][0]['sum(amount)']:0),
                "杀5点":(result[2][0]['sum(amount)']?result[2][0]['sum(amount)']:0),
                "杀6点":(result[3][0]['sum(amount)']?result[3][0]['sum(amount)']:0),
                "杀7点":(result[4][0]['sum(amount)']?result[4][0]['sum(amount)']:0),
                "杀8点":(result[5][0]['sum(amount)']?result[5][0]['sum(amount)']:0),
                "杀9点":(result[6][0]['sum(amount)']?result[6][0]['sum(amount)']:0),
                "杀10点":(result[7][0]['sum(amount)']?result[7][0]['sum(amount)']:0),
                "杀11点":(result[8][0]['sum(amount)']?result[8][0]['sum(amount)']:0),
                "杀12点":(result[9][0]['sum(amount)']?result[9][0]['sum(amount)']:0),
                "杀13点":(result[10][0]['sum(amount)']?result[10][0]['sum(amount)']:0),
                "杀14点":(result[11][0]['sum(amount)']?result[11][0]['sum(amount)']:0),
                "杀15点":(result[12][0]['sum(amount)']?result[12][0]['sum(amount)']:0),
                "杀16点":(result[13][0]['sum(amount)']?result[13][0]['sum(amount)']:0),
                "杀17点":(result[14][0]['sum(amount)']?result[14][0]['sum(amount)']:0),
            }
            var xiazhujinearray = [0,0,0,0,0,0,0,0,0,0,0,0,0] //d x d s dd xd ds xs long hu he shunzi duizi shadian
            if(contant.search("哈")!=-1 && contant.split("哈").length==2){
                if (contant.split("哈")[0]=="" || contant.split("梭哈")[0]=="") {
                    amount = userBalance;
                    guess = contant.split("哈")[1];
                    peilv = 0;
                    if (contant.split("哈")[1]=="大") {
                        peilv = conf.peilv['dxds'];
                        xiazhujinearray[0] += amount
                    }
                    if (contant.split("哈")[1]=="小") {
                        peilv = conf.peilv['dxds'];
                        xiazhujinearray[1] += amount
                    }
                    if (contant.split("哈")[1]=="单") {
                        peilv = conf.peilv['dxds'];
                        xiazhujinearray[2] += amount
                    }
                    if (contant.split("哈")[1]=="双") {
                        peilv = conf.peilv['dxds'];
                        xiazhujinearray[3] += amount
                    }
                    if (contant.split("哈")[1]=="大单") {
                        peilv = conf.peilv['fushi1'];
                        xiazhujinearray[4] += amount
                    }
                    if (contant.split("哈")[1]=="小双") {
                        peilv = conf.peilv['fushi1'];
                        xiazhujinearray[7] += amount
                    }
                    if (contant.split("哈")[1]=="小单") {
                        peilv = conf.peilv['fushi2'];
                        xiazhujinearray[5] += amount
                    }
                    if (contant.split("哈")[1]=="大双") {
                        peilv = conf.peilv['fushi2'];
                        xiazhujinearray[6] += amount
                    }
                    if (contant.split("哈")[1]=="顺子") {
                        peilv = conf.peilv['shunzi'];
                        xiazhujinearray[11] += amount
                    }
                    if (contant.split("哈")[1]=="豹子") {
                        peilv = conf.peilv['baozi'];
                        baozi_xiazhujine=parseInt(amount)
                    }
                    if (contant.split("哈")[1]=="对子") {
                        peilv = conf.peilv['duizi'];
                        xiazhujinearray[12] += amount
                    }
                    if (contant.split("哈")[1]=="龙") {
                        peilv = conf.peilv['longhu'];
                        xiazhujinearray[8] += amount
                    }
                    if (contant.split("哈")[1]=="虎") {
                        peilv = conf.peilv['longhu'];
                        xiazhujinearray[9] += amount
                    }
                    if (contant.split("哈")[1]=="合") {
                        peilv = conf.peilv['he'];
                        xiazhujinearray[10] += amount
                    }

                    if (isfengpan) {
                        bot.sendMessage(conf.chatid, `<b>❌慢！本期已封盘 , 投注无效！</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();
                        return;
                    }
                    if(guess=="" || peilv == 0){
                        connection.destroy();
                        return;
                    }

                    if (userBalance<=0) {
                        bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();
                        return;
                    }

                    if(amount>conf.betMax || amount<conf.betMin){
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限，最大下注金额为${conf.betMax}</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();
                        return;
                    }
                    connection.query(`select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and guess like "豹%" and telegramid = "${telegramid}";select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and guess = "豹子" and telegramid = "${telegramid}";select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and telegramid = "${telegramid}";`,(error, result)=> {
                        if (error) return error;
                        if ((result[0][0]['sum(amount)']?parseFloat(result[0][0]['sum(amount)']):0)+shabaozi_xiazhujine>conf.xianzhu.dianshabaozi) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                reply_to_message_id: replyMessageid,
                                parse_mode:"HTML"
                            })
                            connection.destroy();
                            return
                        }
                        if ((result[1][0]['sum(amount)']?parseFloat(result[1][0]['sum(amount)']):0)+baozi_xiazhujine>conf.xianzhu.baozi) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                reply_to_message_id: replyMessageid,
                                parse_mode:"HTML"
                            })
                            connection.destroy();
                            return
                        }
                        /*if ((result[2][0]['sum(amount)']?parseFloat(result[2][0]['sum(amount)']):0)+xiazhujine>conf.betMax) {
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                reply_to_message_id: replyMessageid,
                                parse_mode:"HTML"
                            })
                            connection.destroy();

                            return
                        }*/
                        connection.query(`select sum(amount) from bet where type = "${conf.type}" and guess = "大" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "小" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "大单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "小单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "大双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "小双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "龙" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "虎" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "合" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "顺子" and telegramid = "${telegramid}" and resultid = "${resultid}";
                        select sum(amount) from bet where type = "${conf.type}" and guess = "对子" and telegramid = "${telegramid}" and resultid = "${resultid}";`,(error, result)=> {
                            if (error) return error;
                            for (let index = 0; index < result.length; index++) {
                                if (parseFloat(result[index][0]['sum(amount)'])+parseFloat(xiazhujinearray[index])>conf.xianzhu.qita) {
                                    connection.destroy();
                                    bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                        reply_to_message_id: replyMessageid,
                                        parse_mode:"HTML"
                                    })
                                    return;
                                }
                            }
                            connection.query(`select * from users where telegramid = "${telegramid}";`,(error, userresult)=> {
                                if (error) return error;
                                if (userresult[0].balance<=0) {
                                    bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`,{
                                        reply_to_message_id: replyMessageid,
                                        parse_mode:"HTML"
                                    })
                                    connection.destroy();
                                    return;
                                }
                                amount = userresult[0].balance;
                                connection.query(`INSERT INTO bet (telegramid ,name ,amount ,guess ,time ,resultid,messageid,firstname,peilv,inviter_telegramid, type) VALUES ("${telegramid}","${name}",${amount},"${guess}",now(),"${resultid}","${replyMessageid}","${utf16toEntities(firstname)}","${peilv}","${userinfo.inviter_telegramid}","${conf.type}");UPDATE users set balance = balance - ${amount}  where telegramid = "${telegramid}";${isnertresultsql}`,(error, result)=> {
                                    if (error) return error;
                                    console.log('insert bet error======',error)
                                    connection.query(`select * from users where telegramid = "${telegramid}";select * from bet where type = "${conf.type}" and  telegramid = "${telegramid}" and resultid = '${resultid}' and result is null;`,(error, result)=> {
                                        console.log('insert bet error2======',error)
                                        connection.destroy();

                                        if (error) throw error;
                                        var quanbutouzhu = "";
                                        for(var index = 0;index<result[1].length;index++){
                                            quanbutouzhu += `<code>${result[1][index].guess}</code>-<code>${result[1][index].amount}</code>(${result[1][index].peilv}倍赔率)\n`
                                        }
                                        bot.sendMessage(conf.chatid, `投注完成后可直接发送🎲进行手摇\n在300秒之内必须手摇完成，否则将会过期不退款\n➖➖➖➖➖➖➖➖➖➖\n您的全部投注：\n${quanbutouzhu}➖➖➖➖➖➖➖➖➖➖\n👤${firstname}  \n💰余额：${(result[0][0].balance)}元`,{
                                            reply_to_message_id: replyMessageid,
                                            parse_mode:"HTML",
                                            reply_markup: {
                                                inline_keyboard: conf.xiazhu_inline_keyboard
                                            },
                                        })
                                    });
                                });
                            });

                        });

                    });
                }


            }else{
                const contantArray = contant.split(/\s+/);
                var allbet = "",amount,guess = "",peilv = "",sql = "INSERT INTO bet (telegramid ,name ,amount ,guess ,time ,resultid,messageid,firstname,peilv,inviter_telegramid,type) VALUES";
                for (let index = 0; index < contantArray.length; index++) {
                    amount = 0,guess = "";
                    if(contantArray[index].search("大单")!=-1 && contantArray[index].split("大单").length==2){
                        if (contantArray[index].split("大单")[0]=="") {
                            amount = contantArray[index].split("大单")[1];
                        }else{
                            amount = contantArray[index].split("大单")[0];
                        }
                        guess = "大单";
                        peilv = conf.peilv['fushi1'];
                        xiazhujinearray[4] += parseInt(amount)
                    }else{
                        if(contantArray[index].search("大")!=-1 && contantArray[index].split("大").length==2){

                            if (contantArray[index].split("大")[0]=="") {
                                amount = contantArray[index].split("大")[1];
                            }else{
                                amount = contantArray[index].split("大")[0];
                            }
                            guess = "大";
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[0] += parseInt(amount)
                        }
                        if(contantArray[index].search("单")!=-1 && contantArray[index].split("单").length==2){
                            if (contantArray[index].split("单")[0]=="") {
                                amount = contantArray[index].split("单")[1];
                            }else{
                                amount = contantArray[index].split("单")[0];
                            }
                            guess = "单";
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[2] += parseInt(amount)
                        }
                    }

                    if(contantArray[index].search("小双")!=-1 && contantArray[index].split("小双").length==2){
                        if (contantArray[index].split("小双")[0]=="") {
                            amount = contantArray[index].split("小双")[1];
                        }else{
                            amount = contantArray[index].split("小双")[0];
                        }
                        guess = "小双";
                        peilv = conf.peilv['fushi1'];
                        xiazhujinearray[7] += parseInt(amount)
                    }else{
                        if(contantArray[index].search("小")!=-1 && contantArray[index].split("小").length==2){
                            if (contantArray[index].split("小")[0]=="") {
                                amount = contantArray[index].split("小")[1];
                            }else{
                                amount = contantArray[index].split("小")[0];
                            }
                            guess = "小";
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[1] += parseInt(amount)
                        }
                        if(contantArray[index].search("双")!=-1 && contantArray[index].split("双").length==2){
                            if (contantArray[index].split("双")[0]=="") {
                                amount = contantArray[index].split("双")[1];
                            }else{
                                amount = contantArray[index].split("双")[0];
                            }
                            guess = "双";
                            peilv = conf.peilv['dxds'];
                            xiazhujinearray[3] += parseInt(amount)
                        }
                    }

                    if(contantArray[index].search("大双")!=-1 && contantArray[index].split("大双").length==2){
                        if (contantArray[index].split("大双")[0]=="") {
                            amount = contantArray[index].split("大双")[1];
                        }else{
                            amount = contantArray[index].split("大双")[0];
                        }
                        guess = "大双";
                        peilv = conf.peilv['fushi2'];
                        xiazhujinearray[6] += parseInt(amount)
                    }

                    if(contantArray[index].search("小单")!=-1 && contantArray[index].split("小单").length==2){
                        if (contantArray[index].split("小单")[0]=="") {
                            amount = contantArray[index].split("小单")[1];
                        }else{
                            amount = contantArray[index].split("小单")[0];
                        }
                        guess = "小单";
                        peilv = conf.peilv['fushi2'];
                        xiazhujinearray[5] += parseInt(amount)
                    }

                    if(contantArray[index].search("豹子")!=-1 && contantArray[index].split("豹子").length==2){
                        if (contantArray[index].split("豹子")[0]=="") {
                            amount = contantArray[index].split("豹子")[1];
                        }else{
                            amount = contantArray[index].split("豹子")[0];
                        }
                        guess = "豹子";
                        peilv = conf.peilv['baozi'];
                        baozi_xiazhujine += parseInt(amount)
                    }
                    if(contantArray[index].search("顺子")!=-1 && contantArray[index].split("顺子").length==2){
                        if (contantArray[index].split("顺子")[0]=="") {
                            amount = contantArray[index].split("顺子")[1];
                        }else{
                            amount = contantArray[index].split("顺子")[0];
                        }
                        guess = "顺子";
                        peilv = conf.peilv['shunzi'];
                        xiazhujinearray[11] += parseInt(amount)
                    }
                    if(contantArray[index].search("对子")!=-1 && contantArray[index].split("对子").length==2){
                        if (contantArray[index].split("对子")[0]=="") {
                            amount = contantArray[index].split("对子")[1];
                        }else{
                            amount = contantArray[index].split("对子")[0];
                        }
                        guess = "对子";
                        peilv = conf.peilv['duizi'];
                        xiazhujinearray[12] += parseInt(amount)
                    }

                    if(contantArray[index].search("龙")!=-1 && contantArray[index].split("龙").length==2){
                        if (contantArray[index].split("龙")[0]=="") {
                            amount = contantArray[index].split("龙")[1];
                        }else{
                            amount = contantArray[index].split("龙")[0];
                        }
                        guess = "龙";
                        peilv = conf.peilv['longhu'];
                        xiazhujinearray[8] += parseInt(amount)
                    }

                    if(contantArray[index].search("虎")!=-1 && contantArray[index].split("虎").length==2){
                        if (contantArray[index].split("虎")[0]=="") {
                            amount = contantArray[index].split("虎")[1];
                        }else{
                            amount = contantArray[index].split("虎")[0];
                        }
                        guess = "虎";
                        peilv = conf.peilv['longhu'];
                        xiazhujinearray[9] += parseInt(amount)
                    }

                    if(contantArray[index].search("合")!=-1 && contantArray[index].split("合").length==2){
                        if (contantArray[index].split("合")[0]=="") {
                            amount = contantArray[index].split("合")[1];
                        }else{
                            amount = contantArray[index].split("合")[0];
                        }
                        guess = "合";
                        peilv = conf.peilv['he'];
                        xiazhujinearray[10] += parseInt(amount)
                    }

                    if(contantArray[index].search("杀")!=-1){
                        if (contantArray[index].split("杀")[0]=="4" || contantArray[index].split("杀")[0]=="5" || contantArray[index].split("杀")[0]=="6" || contantArray[index].split("杀")[0]=="7" || contantArray[index].split("杀")[0]=="8" || contantArray[index].split("杀")[0]=="9" || contantArray[index].split("杀")[0]=="10" || contantArray[index].split("杀")[0]=="11" || contantArray[index].split("杀")[0]=="12" || contantArray[index].split("杀")[0]=="13" || contantArray[index].split("杀")[0]=="14" || contantArray[index].split("杀")[0]=="15" || contantArray[index].split("杀")[0]=="16" || contantArray[index].split("杀")[0]=="17") {
                            if (typeof parseFloat(contantArray[index].split("杀")[1]) === 'number' && !isNaN(contantArray[index].split("杀")[1])  ) {
                                amount = contantArray[index].split("杀")[1];
                                guess = "杀"+contantArray[index].split("杀")[0]+"点";
                                peilv = conf.peilv['s'+contantArray[index].split("杀")[0]+'d'];
                                shuzi_xiazhujine += parseInt(amount)
                                if (shuziamount[guess]+parseFloat(amount)>conf.xianzhu.danshuzi) {
                                    bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                        reply_to_message_id: replyMessageid,
                                        parse_mode:"HTML"
                                    })
                                    connection.destroy();
                                    return;
                                }
                            }
                        }
                    }

                    if(contantArray[index].search("T")!=-1){
                        if (contantArray[index].split("T")[0]=="4" || contantArray[index].split("T")[0]=="5" || contantArray[index].split("T")[0]=="6" || contantArray[index].split("T")[0]=="7" || contantArray[index].split("T")[0]=="8" || contantArray[index].split("T")[0]=="9" || contantArray[index].split("T")[0]=="10" || contantArray[index].split("T")[0]=="11" || contantArray[index].split("T")[0]=="12" || contantArray[index].split("T")[0]=="13" || contantArray[index].split("T")[0]=="14" || contantArray[index].split("T")[0]=="15" || contantArray[index].split("T")[0]=="16" || contantArray[index].split("T")[0]=="17") {
                            if (typeof parseFloat(contantArray[index].split("T")[1]) === 'number' && !isNaN(contantArray[index].split("T")[1])  ) {
                                amount = contantArray[index].split("T")[1];
                                guess = "杀"+contantArray[index].split("T")[0]+"点";
                                peilv = conf.peilv['s'+contantArray[index].split("T")[0]+'d'];
                                shuzi_xiazhujine += parseInt(amount)
                                if (shuziamount[guess]+parseFloat(amount)>conf.xianzhu.danshuzi) {
                                    bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                        reply_to_message_id: replyMessageid,
                                        parse_mode:"HTML"
                                    })
                                    connection.destroy();
                                    return;
                                }
                            }
                        }
                    }

                    if(contantArray[index].search("豹子")!=-1){
                        if (contantArray[index].split("豹子")[0]=="1" || contantArray[index].split("豹子")[0]=="2" || contantArray[index].split("豹子")[0]=="3" || contantArray[index].split("豹子")[0]=="4" || contantArray[index].split("豹子")[0]=="5" || contantArray[index].split("豹子")[0]=="6") {
                            if (parseFloat(contantArray[index].split("豹子")[1])%1 == 0 && !isNaN(contantArray[index].split("豹子")[1])  ) {
                                amount = contantArray[index].split("豹子")[1];
                                guess = "豹子"+contantArray[index].split("豹子")[0]+"点";
                                peilv = conf.peilv['dsbz'];
                                shabaozi_xiazhujine += parseInt(amount)
                            }
                        }
                    }



					xiazhujine += parseInt(amount);
                    if (index==0) {
					sql = sql + ` ("${telegramid}","${name}",${amount},"${guess}",now(),"${resultid}","${replyMessageid}","${utf16toEntities(firstname)}",${peilv},"${userinfo.inviter_telegramid}","${conf.type}")`;
                    } else {
                        sql = sql + ` ,("${telegramid}","${name}",${amount},"${guess}",now(),"${resultid}","${replyMessageid}","${utf16toEntities(firstname)}",${peilv},"${userinfo.inviter_telegramid}","${conf.type}")`;
                    }

                    allbet = allbet + `✅${guess}-${amount}\n`

                    if(amount=="" || /[\u4e00-\u9fa5]+/.test(amount) || /[a-zA-Z]+/.test(amount) || amount%1!=0){
						connection.destroy();
                        return;
                    }
                    if(amount<=0 || guess==""){
						connection.destroy();
                        return;
                    }

                    if(amount>conf.betMax || amount<conf.betMin){
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限，最大下注金额为${conf.betMax}</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
						connection.destroy();
                        return;
                    }

                }

                if (isfengpan) {
                    bot.sendMessage(conf.chatid, `<b>❌慢！本期已封盘 , 投注无效！</b>`,{
                        reply_to_message_id: replyMessageid,
                        parse_mode:"HTML"
                    })
                    connection.destroy();
                    return;
                }

                if (userBalance<xiazhujine) {
                    bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`,{
                        reply_to_message_id: replyMessageid,
                        parse_mode:"HTML"
                    })
					connection.destroy();
                    return;
                }

                connection.query(`select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and guess like "豹%" and telegramid = "${telegramid}";
                select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and guess = "豹子" and telegramid = "${telegramid}";
                select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and telegramid = "${telegramid}";
                select sum(amount) from bet where type = "${conf.type}" and resultid = "${resultid}" and guess like "杀%" and telegramid = "${telegramid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "大" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "小" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "大单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "小单" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "大双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "小双" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "龙" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "虎" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "合" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "顺子" and telegramid = "${telegramid}" and resultid = "${resultid}";
                select sum(amount) from bet where type = "${conf.type}" and guess = "对子" and telegramid = "${telegramid}" and resultid = "${resultid}";`,(error, result)=> {
                    if (error) return error;
                    if ((result[0][0]['sum(amount)']?parseFloat(result[0][0]['sum(amount)']):0)+shabaozi_xiazhujine>conf.xianzhu.dianshabaozi) {
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();
                        return
                    }
                    if ((result[1][0]['sum(amount)']?parseFloat(result[1][0]['sum(amount)']):0)+baozi_xiazhujine>conf.xianzhu.baozi) {
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();
                        return
                    }
                    if ((result[2][0]['sum(amount)']?parseFloat(result[2][0]['sum(amount)']):0)+xiazhujine>conf.danqibetMax) {
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();

                        return
                    }
                    if ((result[3][0]['sum(amount)']?parseFloat(result[3][0]['sum(amount)']):0)+shuzi_xiazhujine>conf.xianzhu.zongshuzi) {
                        bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                            reply_to_message_id: replyMessageid,
                            parse_mode:"HTML"
                        })
                        connection.destroy();

                        return
                    }

                    for (let index = 4; index < result.length-4; index++) {

                        if (parseFloat(result[index][0]['sum(amount)'])+parseFloat(xiazhujinearray[index-4])>conf.xianzhu.qita) {
                            connection.destroy();
                            bot.sendMessage(conf.chatid, `<b>❌投注失败，下注金额超过上限</b>`,{
                                reply_to_message_id: replyMessageid,
                                parse_mode:"HTML"
                            })
                            return;
                        }
                    }

                    connection.query(`select * from users where telegramid = "${telegramid}";`,(error, result)=> {
                        if (error) return error;
                        if (result[0].balance<xiazhujine) {
                            bot.sendMessage(conf.chatid, `<b>❌您的余额不足，请充值后再进行投注!</b>`,{
                                reply_to_message_id: replyMessageid,
                                parse_mode:"HTML"
                            })
                            connection.destroy();
                            return;
                        }
                        connection.query(`${sql};UPDATE users set balance = balance - ${xiazhujine}  where telegramid = "${telegramid}";${isnertresultsql}`,(error, result)=> {
                            console.log(error)
                            if (error) return error;
                            connection.query(`select * from users where telegramid = "${telegramid}";select * from bet where type = "${conf.type}" and  telegramid = "${telegramid}" and resultid = '${resultid}' and result is null;`,(error, result)=> {
                                console.log(`select * from bet where type = "${conf.type}" and  telegramid = "${telegramid}" and resultid = '${resultid}'`)
                                connection.destroy();
                                if (error) return error;
                                var quanbutouzhu = "";
                                for(var index = 0;index<result[1].length;index++){
                                    quanbutouzhu += `${result[1][index].guess}-${result[1][index].amount}元赔率：${result[1][index].peilv}倍\n`
                                }
                                bot.sendMessage(conf.chatid, `投注完成后可直接发送<code>🎲</code>进行手摇\n300秒之内必须手摇完成，否则将会过期不退款\n➖➖➖➖➖➖➖➖➖➖\n您的全部投注：\n${quanbutouzhu}➖➖➖➖➖➖➖➖➖➖\n👤${firstname}  \n💰余额：${(result[0][0].balance)}元`,{
                                    reply_to_message_id: replyMessageid,
                                    parse_mode:"HTML",
                                    reply_markup: {
                                        inline_keyboard: conf.xiazhu_inline_keyboard
                                    },
                                })
                            });
                        });
                    });
                });
            }
        });
    });
}


/*查询流水*/
function getTodayBill(telegramid,name,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";select * from bet where type = "${conf.type}" and telegramid = "${telegramid}" and resultid = '${resultid}';`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            if (result[0].length==0) {

            } else {
				var quanbutouzhu = "";
                for(var index = 0;index<result[1].length;index++){
					quanbutouzhu += `${result[1][index].guess}-${result[1][index].amount}(${result[1][index].peilv}倍赔率)\n`
				}
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `${resultid}期全部投注：\n${quanbutouzhu}`,
                    show_alert:true,
                    cache_time:10
                })
            }
        });

    });
}
function tongji(telegramid,name,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM users where telegramid = "${telegramid}";SELECT sum(amount),sum(result),sum(amountreturn) FROM bet where type = "${conf.type}" and telegramid = "${telegramid}" and time like "${moment(Math.round(date)-1000*60*60*24).format("YYYY-MM-DD")}%";`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            if (!result[0][0]) {
                return
            }
            bot.answerCallbackQuery(callbackQueryid,{
                text: `昨日数据详情\n投注:${(result[1][0]['sum(amount)']?result[1][0]['sum(amount)']:0)}  盈利:${parseInt(result[1][0]['sum(result)']-result[1][0]['sum(amount)']+result[1][0]['sum(amountreturn)']+result[1][0]['sum(amount)']*0.01)}\n反水:${parseInt(result[1][0]['sum(amountreturn)']+result[1][0]['sum(amount)']*0.01)}  回水:${parseInt(result[0][0]['huishui'])}`,
                show_alert:true,
                cache_time:1
            })
            .catch(e=>{
                console.log("领取反水出错");
            })
        });
    });
}

/*领取反水*/
function getfanWater(telegramid,name,callbackQueryid) {

    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT SUM(amount) FROM pay where telegramid = "${telegramid}" and state = 1 and applytime like "${moment(Math.round(date)-1000*60*60*24).format("YYYY-MM-DD")}%";SELECT SUM(amount) FROM withdrawal where telegramid = "${telegramid}" and state = 1 and applytime like "${moment(Math.round(date)-1000*60*60*24).format("YYYY-MM-DD")}%";SELECT * FROM users where telegramid = "${telegramid}";`,(error, result)=> {
            if (error) return error;
            if (!result[2][0]) {
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `领取回水：0 ${conf.coin}`,
                    show_alert:true,
                    cache_time:1
                })
                connection.destroy();
                return
            }
            var shuying = -(result[0][0]['SUM(amount)']?result[0][0]['SUM(amount)']:0) +(result[1][0]['SUM(amount)']?result[1][0]['SUM(amount)']:0)+result[2][0].balance;
            var huishui = 0
            if (shuying<(result[0][0]['SUM(amount)']?result[0][0]['SUM(amount)']:0)*0.05) {
                huishui = (((result[0][0]['SUM(amount)']?result[0][0]['SUM(amount)']:0)-(result[1][0]['SUM(amount)']?result[1][0]['SUM(amount)']:0))*0.03)
            }
            if(result[2][0].lasthuishui==moment().format("YYYY-MM-DD")){
                connection.destroy();
                bot.answerCallbackQuery(callbackQueryid,{
                    text: `您已领取今日回水`,
                    show_alert:true,
                    cache_time:1
                })
                .catch(e=>{
                    console.log("领取回水出错");
                })
            }else{
                connection.query(`UPDATE users set balance = balance + ${huishui},huishui = huishui + ${huishui},lasthuishui = "${moment().format("YYYY-MM-DD")}" where telegramid = "${telegramid}";`,(error, result)=> {
                    connection.destroy();
                    if (error) return error;
                    bot.answerCallbackQuery(callbackQueryid,{
                        text: `领取回水：${huishui} ${conf.coin}`,
                        show_alert:true,
                        cache_time:1
                    })
                    .catch(e=>{
                        console.log("领取回水出错");
                    })
                });
            }

        });
    });
}

/*领取反水*/
function getReturnWater(telegramid,name,callbackQueryid) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM pay where telegramid = "${telegramid}" and state = 1 order by id desc limit 3;SELECT * FROM withdrawal where telegramid = "${telegramid}" and state = 1  order by id desc limit 3;`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            var chongzhi = "充值:\n";
            var tixian = "提现:\n"
            for (let index = 0; index < result[0].length; index++) {
                chongzhi = `${chongzhi}【${result[0][index].applytime.split("2023-")[1].substring(result[0][index].applytime.split("2023-")[1].length-3,result[0][index].applytime.split("2023-")[1])}】${result[0][index].amount}${conf.coin}\n`;
            }
            for (let index = 0; index < result[1].length; index++) {
                tixian = `${tixian}【${result[1][index].applytime.split("2023-")[1].substring(result[1][index].applytime.split("2023-")[1].length-3,result[1][index].applytime.split("2023-")[1])}】${result[1][index].amount}${conf.coin}\n`;
            }
            if (error) return error;
            bot.answerCallbackQuery(callbackQueryid,{
                text: `${(chongzhi=="提现"?"":chongzhi)}\n${(tixian=="提现"?"":tixian)}`,
                show_alert:true,
                cache_time:1
            })
            .catch(e=>{
                console.log("领取反水出错");
            })
        });
    });
}

/*开奖*/
function setResult(msg) {
    conf.pool.getConnection(function(err, connection) {
        console.log('err===',err)
        if (err) return err;
        connection.query(`SELECT * FROM bet where type = "${conf.type}" and telegramid = "${msg.from.id}" and result is null order by id desc;`,(error, result)=> {
            connection.destroy();
            if (result[0]) {
                a = result[0].one
                b = result[0].two
                c = result[0].three
                resultid = result[0].resultid
                resultArray = result
                value = a+b+c;
                /*初始化*/
                resultdxds = {
                    big:0,
                    small:0,
                    odd:0,
                    even:0,
                    baozi:0,
                    shunzi:0,
                    duizi:0
                }
                baozi = "";
                shunzi = "";
                duizi = "";
                daxiao = "";
                danshuang = "";
                longhu = "";



                if  (c-b==1 && b-a==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }
                if  (c-a==1 && b-c==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }
                if  (a-b==1 && c-a==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }
                if  (b-a==1 && a-c==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }
                if  (a-b==1 && b-c==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }
                if  (a-c==1 && c-b==1) {
                    resultdxds.shunzi = 1;
                    shunzi = "顺子";
                }


                if  (a==b && b!=c) {
                    resultdxds.duizi = 1;
                    duizi = "对子";
                }
                if  (b==c && c!=a) {
                    resultdxds.duizi = 1;
                    duizi = "对子";
                }
                if  (a==c && c!=b) {
                    resultdxds.duizi = 1;
                    duizi = "对子";
                }

                if (a==b && b==c && c==a) { //如果是豹，通杀
                    resultdxds.baozi = 1;
                    baozi = "豹子";
                }

                /*大小*/
                if(value>10){
                    resultdxds.big = 1;
                    daxiao = "大";
                }
                if(value<=10){
                    resultdxds.small = 1;
                    daxiao = "小";
                }
                /*单双*/
                if(value%2==1){
                    resultdxds.odd = 1;
                    danshuang = "单";
                }
                if(value%2==0){
                    resultdxds.even = 1;
                    danshuang = "双";
                }

                if (a>c) {
                    resultdxds.longhu = -1;
                    longhu = "龙"
                }else if (a<c) {
                    resultdxds.longhu = 1;
                    longhu = "虎"
                }else{
                    resultdxds.longhu = 0;
                    longhu = "合"
                }

                var allResultMessage = "";
                var allResultSql = "";
                var invitesql = ""
                for (let index = 0; index < resultArray.length; index++) {
                    if (parseInt(resultArray[index].inviter_telegramid)%1==0) {
                        invitesql += `update users set  yongjinbalance = yongjinbalance + ${resultArray[index].amount*conf.yongjin},zhouyongjin = zhouyongjin + ${resultArray[index].amount*conf.yongjin} where telegramid = "${resultArray[index].inviter_telegramid}";insert into jiangli (telegramid,amount,type,time) values ("${resultArray[index].inviter_telegramid}",${resultArray[index].amount*conf.yongjin},"下级${resultArray[index].telegramid}快三佣金奖励",now());`;
                    }
                }
                for (let index = 0; index < resultArray.length; index++) {
                    var allResult = resultArray[index];

                    if (allResult.guess=="大" || allResult.guess=="小" || allResult.guess=="单" || allResult.guess=="双") {
                        if (allResult.guess==daxiao || allResult.guess==danshuang) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="大单"){
                        if (value==11 || value==13 || value==15 || value==17) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="小双"){
                        if (value==4 || value==6 || value==8 || value==10) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="大双"){
                        if (value==12 || value==14 || value==16 || value==18) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }
                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="小单"){
                        if (value==3 || value==5 || value==7 || value==9) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="豹子"){
                        if (resultdxds.baozi == 1) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount-allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="顺子"){
                        if(resultdxds.shunzi == 1) {
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }
                    if (allResult.guess=="对子"){
                        if(resultdxds.duizi == 1) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }

                    if (allResult.guess.search("杀")!=-1 && allResult.guess.search("点")!=-1){
                        if (parseInt(allResult.guess.split("点")[0].split("杀")[1])==value) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount-allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }
                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }

                    if (allResult.guess.search("豹子")!=-1 && allResult.guess.search("点")!=-1){
                        if (parseInt(allResult.guess.split("点")[0].split("豹子")[1])==value/3 && resultdxds.baozi == 1) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount-allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }

                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }

                    if (allResult.guess=="龙" || allResult.guess=="虎" || allResult.guess=="合") {
                        if (longhu==allResult.guess) {
                            if (resultdxds.shunzi == 1 || value==10 || value==11) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else if (allResult.guess=="龙" || allResult.guess=="虎") {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }
                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }

                    if (allResult.guess=="合") {
                        if (longhu==allResult.guess) {
                            if (false) {
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>回本 +${parseInt(1.7*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${1.7*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(1.7*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(1.7*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }else{
                                allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b>中奖了！ +${parseInt(allResult.peilv*allResult.amount)}</b>\n`
                                allResultSql = `${allResultSql}update bet set result = ${allResult.peilv*allResult.amount} where id = ${allResult.id};update users set balance = balance + ${parseInt(allResult.peilv*allResult.amount)},todayhuishui = todayhuishui - ${parseInt(allResult.peilv*allResult.amount-allResult.amount+conf.allreturnwater*allResult.amount)},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount},lastbet_time = now() where telegramid = "${allResult.telegramid}";`
                            }
                        }else{
                            allResultMessage = `${allResultMessage}${parseInt(allResult.amount)}-${allResult.guess} <b> 输 -${parseInt(allResult.amount)}</b>\n`
                            allResultSql = `${allResultSql}update bet set result = 0 where id = ${allResult.id};update users set lastbet_time = now(),todayhuishui = todayhuishui + ${allResult.amount-conf.allreturnwater*allResult.amount},liushui = liushui + ${allResult.amount},zongliushui = zongliushui + ${allResult.amount} where telegramid = "${allResult.telegramid}";`
                        }
                    }

                }
                conf.pool.getConnection(function(err, connection) {
                    if (err) {
                        bot.sendMessage(conf.chatid, `${resultid}期接口不稳定，此期投注仍有效，联系客服处理`,{
                            reply_markup: JSON.stringify({
                            inline_keyboard: conf.inline_keyboard
                            })
                        });
                        console.log(err);
                        return;
                    } ;

                    connection.query(`update result set big = ${resultdxds.big} ,small = ${resultdxds.small} ,odd = ${resultdxds.odd},even = ${resultdxds.even},baozi = ${resultdxds.baozi},shunzi = ${resultdxds.shunzi},duizi = ${resultdxds.duizi},longhu = "${longhu}" where id = "${resultid}";${allResultSql}${invitesql}`,(error, result)=> {

                        if (error) {
                            bot.sendMessage(conf.chatid, `${resultid}期接口不稳定，此期投注仍有效，联系客服处理`,{
                                reply_markup: JSON.stringify({
                                inline_keyboard: conf.inline_keyboard
                                })
                            });
                            console.log(error);
                            return;
                        }
                        connection.query(`SELECT * FROM result where type = "${conf.type}" order by result_time desc LIMIT 20;select * from users where telegramid = "${msg.from.id}";`,(error, result)=> {
                            if (error) return error;
                            console.log(error)
                            connection.destroy()
                            if (allResultMessage.length>600) {
                                allResultMessage = allResultMessage.substring(0,600);
                                allResultMessage += `...等${resultArray.length}次投注\n`
                            }
                            var quanbutouzhu = ""
                            for (let index = 0; index < resultArray.length; index++) {
                                quanbutouzhu += `${resultArray[index].guess}-${resultArray[index].amount}元 赔率：${resultArray[index].peilv}倍\n`;
                            }
                            var sendruselttxt = `${a}+${b}+${c}=${a+b+c}  结果-${daxiao}-${danshuang}-${(baozi==""?baozi:" "+baozi+" ")}${(shunzi==""?shunzi:" "+shunzi)}${(duizi==""?duizi:" "+duizi)}-${longhu}\n🧧㊗️老板们多多盈利，美金越来越多💵💵💵🧧\n————老板中奖————\n${allResultMessage}-----------\n您的余额:${result[1][0].balance}元 `;
                            setTimeout(function() {
                                bot.sendMessage(conf.chatid,`结果已录入，点数：${a}+${b}+${c}=${a+b+c} ${longhu}\n您的全部投注如下：\n${quanbutouzhu}`,{
                                    reply_to_message_id:msg.message_id
                                })
                                .then(res=>{
                                    bot.sendMessage(conf.chatid,sendruselttxt,{
                                        parse_mode:"HTML",
                                        disable_web_page_preview:true,
                                        reply_to_message_id:msg.message_id,
                                        reply_markup: JSON.stringify({
                                            inline_keyboard: conf.guize_inline_keyboard
                                        })
                                    })
                                })
                            },1000)
                        });
                    });
                });
            }
        });
    });
}


function utf16toEntities(str) {
    const patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
    str = str.replace(patt, (char) => {
      let H;
      let L;
      let code;
      let s;

      if (char.length === 2) {
        H = char.charCodeAt(0); // 取出高位
        L = char.charCodeAt(1); // 取出低位
        code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
        s = `&#${code};`;
      } else {
        s = char;
      }

      return s;
    });

    return str;
}

function entitiestoUtf16(strObj) {
    const patt = /&#\d+;/g;
    const arr = strObj.match(patt) || [];

    let H;
    let L;
    let code;

    for (let i = 0; i < arr.length; i += 1) {
      code = arr[i];
      code = code.replace('&#', '').replace(';', '');
      // 高位
      H = Math.floor((code - 0x10000) / 0x400) + 0xD800;
      // 低位
      L = ((code - 0x10000) % 0x400) + 0xDC00;
      code = `&#${code};`;
      const s = String.fromCharCode(H, L);
      strObj = strObj.replace(code, s);
    }
    return strObj;
}



function paiming(chatid) {
	conf.pool.getConnection(function(err, connection) {
		if (err) return err;
		connection.query(`SELECT nickname,todayhuishui, jndtodayhuishui, (todayhuishui + jndtodayhuishui + pctodayhuishui) AS sum FROM users where (todayhuishui + jndtodayhuishui + pctodayhuishui) < 0 ORDER BY sum asc limit 5;`,(error, result)=> {
			if (error) return error;
			connection.destroy();
			var paiminglist = "";
			for (let index = 0; index < result.length; index++) {
				if (index==0) {
					paiminglist += `🥇 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
				}else if(index==1){
					paiminglist += `🥈 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
				}else if(index==2){
					paiminglist += `🥉 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
				}else{
					paiminglist += `🎖 【${result[index].nickname}】 老板盈利【${-result[index].sum}】💵\n\n`
				}
			}
			bot.sendPhoto(chatid,'./img/phb.jpg',{
				parse_mode: 'HTML',
				disable_web_page_preview:true,
                reply_markup:{
                    inline_keyboard:conf.yjc_inline_keyboard
                },
				caption:`🔥🔥今日总战报  🔥🔥\n\n当月玩家总下分100wU\n当月玩家盈利金额50wU\n🏆今日截止目前盈利玩家排行榜前五名🏆\n\n${paiminglist}\n🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨\n恭喜以上截至目前最高盈利的老板，\n祝各老板们日进斗金，腰缠万贯，八方来财，荷包满满\n欢迎各位老板踊跃提款，\n为各位老板提供最好的服务\n🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨🧨`
			})
            .then(res=>{
                if (res.chat.id==conf.chatid) {
                    bot.pinChatMessage(res.chat.id,res.message_id)
                }
            })
		});
	})
}



function getlastday(lastday) {
    return moment(Math.round(new Date)-lastday*60*60*24*1000).format("YYYY-MM-DD 00:%")
}
app.get('/table/pay/go',(req,res)=>{

    conf.pool.getConnection(function(err, connection) {
        var params = JSON.parse(req.query.data);
        if(err){
            common.reqError(res);
        }else if(common.oc(req)){
            connection.query(`select * from pay where id = ${params.id};`,(error, result)=> {
                if (error){
                    common.reqError(res);
                }else{
                    if (!result[0]) {
                        res.send({
                            code:400,
                            msg:"该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state!=0) {
                        res.send({
                            code:400,
                            msg:"该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update pay set state = 1 , changetime = now() where id = ${params.id};update users set balance = balance + ${params.amount} where telegramid = ${params.telegramid};`,(error, result)=> {
                            if (error){
                                common.reqError(res);
                            }else{
                                connection.query(`select * from pay where id = ${params.id};SELECT * FROM users where telegramid = "${params.telegramid}";`,(error, result)=> {
                                    connection.destroy();
                                    if (error){
                                        common.reqError(res);
                                    }else{
                                        res.send({
                                            code:200,
                                            msg:result[0]
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `您的上分申请已通过，当前余额${result[1][0].balance}，祝您游戏愉快`,{
                                                reply_to_message_id:result[0][0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }else{
            common.reqError(res);
        }
    });
})



app.get('/table/pay/refuse',(req,res)=>{
    conf.pool.getConnection(function(err, connection) {
        var params = JSON.parse(req.query.data);
        if(err){
            common.reqError(res);
        }else if(common.oc(req)){
            connection.query(`select * from pay where id = ${params.id};`,(error, result)=> {
                if (error){
                    common.reqError(res);
                }else{
                    if (!result[0]) {
                        res.send({
                            code:400,
                            msg:"该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state!=0) {
                        res.send({
                            code:400,
                            msg:"该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update pay set state = -1 , changetime = now() where id = ${params.id};`,(error, result)=> {
                            if (error){
                                common.reqError(res);
                            }else{
                                connection.query(`select * from pay where id = ${params.id};`,(error, result)=> {
                                    connection.destroy();
                                    if (error){
                                        common.reqError(res);
                                    }else{
                                        res.send({
                                            code:200,
                                            msg:result
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `上分失败，金额：${params.amount}`,{
                                                reply_to_message_id:result[0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }else{
            common.reqError(res);
        }
    });
})

app.get('/table/withdrawal/go',(req,res)=>{
    conf.pool.getConnection(function(err, connection) {
        var params = JSON.parse(req.query.data);
        if(err){
            common.reqError(res);
        }else if(common.oc(req)){
            connection.query(`select * from withdrawal where id = ${params.id};`,(error, result)=> {
                if (error){
                    common.reqError(res);
                }else{
                    if (!result[0]) {
                        res.send({
                            code:400,
                            msg:"该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state!=0) {
                        res.send({
                            code:400,
                            msg:"该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update withdrawal set state = 1, changetime = now() where id = ${params.id};`,(error, result)=> {
                            if (error){
                                common.reqError(res);
                            }else{
                                connection.query(`select * from withdrawal where id = ${params.id};SELECT * FROM users where telegramid = "${params.telegramid}";`,(error, result)=> {
                                    connection.destroy();
                                    if (error){
                                        common.reqError(res);
                                    }else{
                                        res.send({
                                            code:200,
                                            msg:result[0]
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `您的下分申请已通过,当前余额${result[1][0].balance},欢迎再次光临`,{
                                                reply_to_message_id:result[0][0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }else{
            common.reqError(res);
        }
    });
})

app.get('/table/withdrawal/refuse',(req,res)=>{
    conf.pool.getConnection(function(err, connection) {
        var params = JSON.parse(req.query.data);
        if(err){
            common.reqError(res);
        }else if(common.oc(req)){
            connection.query(`select * from withdrawal where id = ${params.id};`,(error, result)=> {
                if (error){
                    common.reqError(res);
                }else{
                    if (!result[0]) {
                        res.send({
                            code:400,
                            msg:"该订单已删除，操作失败"
                        })
                        return
                    }
                    if (result[0].state!=0) {
                        res.send({
                            code:400,
                            msg:"该订单已操作，请勿重复操作"
                        })
                    } else {
                        connection.query(`update withdrawal set state = -1 , changetime = now() where id = ${params.id};update users set balance = balance + ${params.amount} where telegramid = ${params.telegramid};`,(error, result)=> {
                            if (error){
                                common.reqError(res);
                            }else{
                                connection.query(`select * from withdrawal where id = ${params.id};`,(error, result)=> {
                                    connection.destroy();
                                    if (error){
                                        common.reqError(res);
                                    }else{
                                        res.send({
                                            code:200,
                                            msg:result
                                        })
                                        if (conf.issendsxf) {
                                            bot.sendMessage(conf.sxfqunid, `下分失败，金额：${params.amount}`,{
                                                reply_to_message_id:result[0].replyMessageid
                                            });
                                        }
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }else{
            common.reqError(res);
        }
    });
})


function listenUSDTOrder() {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM pay where applytimestamp <= unix_timestamp()-600 and state = 0;update pay set state = -1 where applytimestamp <= unix_timestamp()-600 and state = 0;`,(error, result)=> {
            connection.destroy();
            if (error) return error;
            for (let index = 0; index < result[0].length; index++) {
                bot.sendMessage(result[0][index].telegramid, `此订单已过期，请重新获取订单`,{
                    parse_mode: 'HTML',
                    reply_to_message_id: result[0][index].replyMessageid
                })
            }
        });
    })
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`SELECT * FROM pay where applytimestamp > unix_timestamp()-600 and state = 0;SELECT * FROM pay where applytimestamp >= unix_timestamp()-600 and state = 1;`,(error, result)=> {
            if (error) return error;
            connection.destroy();
            var resultsuccess = []
            for (let index = 0; index < result[1].length; index++) {
                resultsuccess.push(result[1][index].transaction_id)
            }
            var sql = "";
            for (let index = 0; index < result[0].length; index++) {

                request(apitrc)
                .then((body)=>{
                    for (let i = 0; i < JSON.parse(body).data.length; i++) {
                        if (JSON.parse(body).data[i].type=="Transfer" && JSON.parse(body).data[i].to==conf.czaddress && (JSON.parse(body).data[i].value)/1000000==result[0][index].amount && (JSON.parse(body).data[i].block_timestamp)/1000+600>parseInt(result[0][index].applytimestamp)) {
                            var issame = false;
                            for (let a = 0; a < resultsuccess.length; a++) {
                                if (resultsuccess[a]==JSON.parse(body).data[i].transaction_id) {
                                    issame = true
                                }

                            }
                            if (!issame) {
                                sql = sql+ `update pay set state = 1,transaction_id = "${JSON.parse(body).data[i].transaction_id}" where applytimestamp = '${result[0][index].applytimestamp}';update users set balance = balance+${(result[0][index].amount*6.75).toFixed(2)} where telegramid = '${result[0][index].telegramid}';`;
                                bot.editMessageText(`<b>充值成功，金额： ${result[0][index].amount} USDT = ${(result[0][index].amount*6.75).toFixed(2)} RMB</b>`,{
                                    parse_mode: 'HTML',
                                    message_id: result[0][index].replyMessageid,
                                    chat_id:result[0][index].telegramid
                                })
                                if (conf.isnoticegroup) {
                                    bot.sendMessage(conf.sxfgroupid, `用户：${result[0][index].name}\nID：${result[0][index].telegramid}\n使用机器人上分成功！\n上分金额：${(result[0][index].amount).toFixed(2)}USDT = ${(result[0][index].amount*6.75).toFixed(2)} RMB\n祝您一路长虹！`,{
                                        parse_mode: 'HTML',
                                    })
                                }
                            }
                        }
                        if (index == result[0].length-1 && sql != "" && i == JSON.parse(body).data.length-1) {
                            conf.pool.getConnection(function(err, connection) {
                                if (err) return err;
                                connection.query(`${sql}`,(error, res)=> {
                                    connection.destroy();
                                    if (error) return error;
                                });
                            })
                        }else if(index == result[0].length-1 && sql == "" && i == JSON.parse(body).data.length-1){

                        }
                    }
                })
                .catch((err)=>{
                    console.log(err);
                })
            }
        });
    })
}

function qxorder(callbackQuery) {
    conf.pool.getConnection(function(err, connection) {
        if (err) return err;
        connection.query(`update pay set state = -1 where replyMessageid = "${callbackQuery.message.message_id}";`,(error, result)=> {
            connection.destroy();
            if (error) {
                console.log(error);
                return
            };
            bot.editMessageText(`🔁<b>您的充值订单已成功取消</b>`, {
                chat_id: callbackQuery.from.id,
                message_id: callbackQuery.message.message_id,
                parse_mode:"HTML"
            }).catch(err=>{
                console.log(err);
            });
        });
    })
}

async function transferUSDT(trx_address,amount) {
    const {
        abi
    } = await tronWeb.trx.getContract(contractaddress_usdt);

    const contract = tronWeb.contract(abi.entrys, contractaddress_usdt);
    hashid = await contract.methods.transfer(trx_address, amount*1000000).send();
    console.log(hashid);


}


function yongjinpaiming(chatid) {
	conf.pool.getConnection(function(err, connection) {
		if (err) return err;
		connection.query(`SELECT * FROM users where zongyongjin > 0 ORDER BY zongyongjin desc limit 10;select * from yongjinchi where id = 1;`,(error, result)=> {
			if (error) return error;
			connection.destroy();
			var paiminglist = "";
			for (let index = 0; index < result[0].length; index++) {
                if (index==0) {
                    paiminglist += `🥇 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.37).toFixed(2)}</code>\n\n`
                }else if(index==1){
                    paiminglist += `🥈 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.25).toFixed(2)}</code>\n\n`
                }else if(index==2){
                    paiminglist += `🥉 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.15).toFixed(2)}</code>\n\n`
                }else if(index==3){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.10).toFixed(2)}</code>\n\n`
                }else if(index==4){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.05).toFixed(2)}</code>\n\n`
                }else if(index==5){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.03).toFixed(2)}</code>\n\n`
                }else if(index==6){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.02).toFixed(2)}</code>\n\n`
                }else if(index==7){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                }else if(index==8){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                }else if(index==9){
                    paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                }
            }
			bot.sendPhoto(chatid,'./img/yjc.jpg',{
                parse_mode: 'HTML',
                disable_web_page_preview:true,
                caption:`<b>🧧🧧🧧佣金排行榜🧧🧧🧧</b>\n\n（按照下级充值金额排名）\n\n本周待分红奖池 <code>${result[1][0].amount}</code> 元\n\n${paiminglist}\n\n\n最低每星期佣金分红3000rmb\n推出佣金池活动 从推广链接进来的用户永久返利上级1%   并且充值的百分之5拿来投入佣金池中 \n推广的客户充值和投注是永久有效的\n每周日只清理佣金池分红‼️\n进入  @shouyaokuaisanbot\n发送/start  点击代理中心生成群链接\n佣金池排行榜也可查看\n每星期天晚上00.00分红发放佣金   佣金可直接提现\n🔥恒旺佣金排行榜🔥🎉🎉🎉\n\n发现用小号刷佣金的，一律无效清除\n禁止违规操作❗️❗️❗️❗️❗️❗️`,
                reply_markup:{
                    inline_keyboard:conf.yjc_inline_keyboard
                }
            })
            .then(res=>{
                bot.pinChatMessage(res.chat.id,res.message_id)
            })
		});
	})
}


function yongjinpaiminguser(chatid) {
	conf.pool.getConnection(function(err, connection) {
		if (err) return err;
		connection.query(`SELECT * FROM users where zongyongjin > 0 ORDER BY zongyongjin desc limit 10;select * from yongjinchi where id = 1;select * from users where telegramid = "${chatid}";`,(error, result)=> {
			if (error) return error;
			connection.query(`SELECT count(*) FROM users where zongyongjin > ${result[2][0].zongyongjin};`,(error, res)=> {
                if (error) return error;
                connection.destroy();
                var paiminglist = "";
                var isqianshi = false
                var yujifenhong = 0
                for (let index = 0; index < result[0].length; index++) {
                    if (result[0][index].telegramid==chatid) {
                        isqianshi = true
                        if (index==0) {
                            yujifenhong = result[1][0].amount*0.37
                        }else if(index==1){
                            yujifenhong = result[1][0].amount*0.25
                        }else if(index==2){
                            yujifenhong = result[1][0].amount*0.15
                        }else if(index==3){
                            yujifenhong = result[1][0].amount*0.10
                        }else if(index==4){
                            yujifenhong = result[1][0].amount*0.05
                        }else if(index==5){
                            yujifenhong = result[1][0].amount*0.03
                        }else if(index==6){
                            yujifenhong = result[1][0].amount*0.02
                        }else if(index==7){
                            yujifenhong = result[1][0].amount*0.01
                        }else if(index==8){
                            yujifenhong = result[1][0].amount*0.01
                        }else if(index==9){
                            yujifenhong = result[1][0].amount*0.01
                        }
                    }
                    if (index==0) {
                        paiminglist += `🥇 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.37).toFixed(2)}</code>\n\n`
                    }else if(index==1){
                        paiminglist += `🥈 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.25).toFixed(2)}</code>\n\n`
                    }else if(index==2){
                        paiminglist += `🥉 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.15).toFixed(2)}</code>\n\n`
                    }else if(index==3){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.10).toFixed(2)}</code>\n\n`
                    }else if(index==4){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.05).toFixed(2)}</code>\n\n`
                    }else if(index==5){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.03).toFixed(2)}</code>\n\n`
                    }else if(index==6){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.02).toFixed(2)}</code>\n\n`
                    }else if(index==7){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                    }else if(index==8){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                    }else if(index==9){
                        paiminglist += `🎖 【${result[0][index].nickname}】，本周佣金 <code>${result[0][index].zhouyongjin}</code>，预计分红 <code>${(result[1][0].amount*0.01).toFixed(2)}</code>\n\n`
                    }
                }
                bot.sendPhoto(chatid,'./img/yjc.jpg',{
                    parse_mode: 'HTML',
                    disable_web_page_preview:true,
                    caption:`<b>🧧🧧🧧佣金排行榜🧧🧧🧧</b>\n\n（按照下级充值金额排名）\n\n本周待分红奖池 <code>${result[1][0].amount}</code> 元\n\n${paiminglist}\n\n我的排名 <code>${res[0]['count(*)']+1}</code>，预计分红 <code>${yujifenhong}</code> 元\n\n发现用小号刷佣金的，一律无效清除\n禁止违规操作❗️❗️❗️❗️❗️❗️`
                })
            });
		});
	})
}
